﻿using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Runtime.Session;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bom;
using Camc.Quality.Bop;
using Camc.Quality.Bop.TreeObject;
using Camc.Quality.Common;
using Camc.Quality.DataDictionary;
using Camc.Quality.Dto;
using Camc.Quality.IOperationHistory;
using Camc.Quality.Materials;
using Camc.Quality.OperationHistory;
using Camc.Quality.ProductionPlan;
using Camc.Quality.Quality;
using Camc.Quality.RecordTable.FormClass;
using Camc.Quality.StoreManagement;
using Camc.Quality.StoreManagement.StoragePut;
using Camc.Quality.StoreManagement.StoreInfo;
using Camc.Quality.TrepanningManager.BomAnalyse;
using Camc.Quality.TrepanningManager.BomNestingInterface;
using Camc.Quality.TrepanningManager.CollectBom;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using static Camc.Quality.StoreManagement.StoragePut.StoreStockContent;

namespace Camc.Quality.TrepanningManager.MatingManager
{
    public class MatingManagerAppService : QualityAppServiceBase
    {
        public List<TreeClass> treeNodes = new List<TreeClass>();
        private readonly IRepository<BopNode, Guid> _bopNodeRepository;
        private readonly IRepository<BopDesc, Guid> _bopDescRepository;
        private readonly IRepository<BopContent, Guid> _bopContentRepository;
        private readonly IRepository<LoadPieceEntity, Guid> _loadPieceRepository;
        private readonly IRepository<ProcessesEntity, Guid> _processesEntityRepository;
        private readonly IRepository<WorkStepEntity, Guid> _workStepEntityRepository;
        private readonly IRepository<User, long> _userRepository;
        private readonly IRepository<BomDesign, Guid> _bomDesignrepository;
        private readonly IRepository<BomDesignDetail, Guid> _bomDesignDetailrepository;
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IRepository<TechniqueEntity, Guid> _techniqueEntityRepository;
        public readonly IRepository<StoreStock, Guid> _storeStockRepsitory;
        public readonly IRepository<StoreStockContent, Guid> _storeStockContentRepsitory;
        private readonly IRepository<MaterialsNode, Guid> _materialsNodeRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        public readonly IRepository<StorePutContent, Guid> _storePutContentRepository;
        public readonly IBomMatingExportToExcel _bomMatingExportToExcelRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IRepository<CollectBomManagerChild, Guid> _collectBomManagerChildRepository;
        private readonly IAbpSession _abpSession;
        private readonly IRepository<CollectBomManager, Guid> _collectBomManagerRepository;
        private readonly CollectBomAppService _collectBomAppService;
        private readonly BomAnalyseAppService _bomAnalyseAppServiceRepository;
        // private readonly IRoute _iRoute;
        private readonly ProductionDesignAppService _productionDesignAppService;
        private readonly IRepository<ProductionScheduler, Guid> _productionSchedulerRepository;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        private readonly StoreFunctionsAppService _storeFunctionsAppService;
        private List<MatingEditParentData> bomMakeEditChildDatas = new List<MatingEditParentData>();
        public MatingManagerAppService(
          // IRoute iRoute,
          IRepository<BopNode, Guid> bopNodeRepository,
          IRepository<BopDesc, Guid> bopDescRepository,
          IRepository<BopContent, Guid> bopContentRepository,
          IRepository<ProcessesEntity, Guid> processesEntityRepository,
          IRepository<WorkStepEntity, Guid> workStepEntityRepository, IRepository<LoadPieceEntity, Guid> loadPieceRepository, IRepository<User, long> userRepository, IRepository<BomDesign, Guid> bomDesignrepository, IRepository<BomDesignDetail, Guid> bomDesignDetailrepository, IRepository<MaterialsContent, Guid> materialsContentRepository, IRepository<TechniqueEntity, Guid> techniqueEntityRepository, IRepository<StoreStock, Guid> storeStockRepsitory, IRepository<StoreStockContent, Guid> storeStockContentRepsitory, IRepository<MaterialsNode, Guid> materialsNodeRepository, IRepository<Sys_Code, Guid> sysCodeRepository, IAbpSession abpSession, IRepository<StorePutContent, Guid> storePutContentRepository, ProductionDesignAppService productionDesignAppService, IBomMatingExportToExcel bomMatingExportToExcelRepository, IUnitOfWorkManager unitOfWorkManager, IRepository<CollectBomManagerChild, Guid> collectBomManagerChildRepository, IRepository<CollectBomManager, Guid> collectBomManagerRepository, CollectBomAppService collectBomAppService, BomAnalyseAppService bomAnalyseAppServiceRepository,
            IRepository<ProductionScheduler, Guid> productionSchedulerRepository, OperationHistoryAppService iOperationHistoryAppService, StoreFunctionsAppService storeFunctionsAppService)
        {
            this._bopNodeRepository = bopNodeRepository;
            this._bopDescRepository = bopDescRepository;
            this._bopContentRepository = bopContentRepository;
            this._processesEntityRepository = processesEntityRepository;
            this._workStepEntityRepository = workStepEntityRepository;
            this._loadPieceRepository = loadPieceRepository;
            this._userRepository = userRepository;
            this._bomDesignDetailrepository = bomDesignDetailrepository;
            this._bomDesignrepository = bomDesignrepository;
            this._materialsContentRepository = materialsContentRepository;
            this._techniqueEntityRepository = techniqueEntityRepository;
            this._storeStockRepsitory = storeStockRepsitory;
            this._storeStockContentRepsitory = storeStockContentRepsitory;
            this._materialsNodeRepository = materialsNodeRepository;
            this._sysCodeRepository = sysCodeRepository;
            this._abpSession = abpSession;
            this._storePutContentRepository = storePutContentRepository;
            //_iRoute = iRoute;
            this._productionDesignAppService = productionDesignAppService;
            this._bomMatingExportToExcelRepository = bomMatingExportToExcelRepository;
            this._unitOfWorkManager = unitOfWorkManager;
            this._collectBomManagerChildRepository = collectBomManagerChildRepository;
            this._collectBomManagerRepository = collectBomManagerRepository;
            this._collectBomAppService = collectBomAppService;
            this._bomAnalyseAppServiceRepository = bomAnalyseAppServiceRepository;
            this._productionSchedulerRepository = productionSchedulerRepository;
            this._iOperationHistoryAppService = iOperationHistoryAppService;
            this._storeFunctionsAppService = storeFunctionsAppService;
        }
        /// <summary>
        /// 配套显示
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public MatingTreeResult DisplayMatingNodeDetails(PartsOutboundInput input)
        {
            MatingTreeResult result = new MatingTreeResult();
            if (input.NodeId != Guid.Empty)
            {
                int route = GetRouteType(input.NodeId);
                List<MatingTreeGridDto> outputs = new List<MatingTreeGridDto>();
                var loadQuery = _loadPieceRepository.GetAll().ToList();
                var querySysCode = _sysCodeRepository.GetAll().ToList();
                var queryStoreStockList = _storeStockRepsitory.GetAll().ToList();
                // select new
                //{
                //    Id = temp.Id,
                //    Number = temp.Number,
                //    WorkStepEntityId = temp.WorkStepEntityId,
                //    Sort = temp.Sort
                //};
                //var storeStocks = _storeStockRepsitory.GetAll();
                var stockContent = _storeStockContentRepsitory.GetAll().ToList();
                var queryMaterialsContent = _materialsContentRepository.GetAll().ToList();
                var queryWorkStepEntity = _workStepEntityRepository.GetAll().ToList();
                int Level = 0;
                switch (route)
                {
                    case 1:
                    case 2:
                        var bopNodes = _bopNodeRepository.GetAll().Where(d => d.ParentId == input.NodeId).OrderBy(d => d.CreationTime).ToList();
                        if (bopNodes.Count() > 0)
                        {

                            foreach (var item in bopNodes)
                            {
                                int ProcessDosage = 0;
                                int SuiteStock = 0;
                                int OutboundedNum = 0;
                                int OutboundQuantity = 0;
                                int ShortageNum = 0;
                                string AssortState = "";
                                string matingName = "";
                                List<MatingDetaillist> matingDetaillists = new List<MatingDetaillist>();
                                //获取该部套下的工艺规程id
                                var techQuery = _bopNodeRepository.GetAll().Where(d => d.NodeCode.StartsWith(item.NodeCode) && d.BopDescId == item.BopDescId).Where(d => d.TechniqueEntityId != null).Select(d => d.TechniqueEntityId).ToList();
                                if (techQuery.Count > 0)
                                {
                                    var moduleLotNo = _bopDescRepository.FirstOrDefaultAsync(t => t.Id == item.BopDescId).Result;
                                    //根据工艺规程id获取部套下所有的工步
                                    var workIds = queryWorkStepEntity.Where(d => techQuery.Contains(d.TechniqueEntityId)).Select(d => d.Id);
                                    //获取工步下所有装入件
                                    var loadData = from loadPieceList in loadQuery.Where(d => workIds.Contains(d.WorkStepEntityId)).OrderBy(d => d.Sort)
                                                   join materialsList in queryMaterialsContent on loadPieceList.MaterialsContentId equals materialsList.Id
                                                   select loadPieceList;
                                    CollectBomManager collectBomManager = new CollectBomManager();
                                    BopNode bop = new BopNode();
                                    ProcessDosage = (from loadPieceList in loadData.Where(d => workIds.Contains(d.WorkStepEntityId)) select loadPieceList).Sum(t => t.Number);

                                    if (item.ParentCode == "root")
                                    {
                                        collectBomManager = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.XJName == item.NodeName && t.XJDrawingNo == item.NodeDrawingNo && t.ModuleId == moduleLotNo.ModelId && t.SendTimeId == moduleLotNo.LotNoId).Result;
                                        bop = _bopNodeRepository.GetAll().Where(d => d.Id == item.Id).FirstOrDefault();
                                    }
                                    else
                                    {
                                        bop = _bopNodeRepository.GetAll().Where(d => d.NodeCode == item.ParentCode.Substring(0, 3) && d.BopDescId == item.BopDescId).FirstOrDefault();

                                        collectBomManager = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.XJName == bop.NodeName && t.XJDrawingNo == bop.NodeDrawingNo && t.ModuleId == moduleLotNo.ModelId && t.SendTimeId == moduleLotNo.LotNoId).Result;
                                    }
                                    //找出该芯级下所有的规程id
                                    var techQueryThwo = _bopNodeRepository.GetAll().Where(d => d.ParentCode.StartsWith(bop.NodeCode) && d.BopDescId == bop.BopDescId).Where(d => d.TechniqueEntityId != null).Select(d => d.TechniqueEntityId).ToList();
                                    //根据规程id获取所有工步
                                    var workIdsTwoAll = queryWorkStepEntity.Where(d => techQueryThwo.Contains(d.TechniqueEntityId)).Select(d => d.Id);
                                    //找出该芯级下所有的装入件
                                    var loadListTwo = (from cc in loadQuery
                                                       join mm in workIdsTwoAll on cc.WorkStepEntityId equals mm
                                                       select cc).ToList();
                                    if (collectBomManager == null)
                                    {
                                        result.Message = "该芯级下没有汇总数据，请检查";
                                        result.code = 1;
                                        return result;
                                    }
                                    var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectBomManager.XJId);
                                    if (collectBomMaterialsContentDtos == null)
                                    {
                                        result.Message = "该芯级下没有汇总数据，请检查";
                                        result.code = 1;
                                        return result;
                                    }
                                    //找到这个芯级下所有的库存信息 汇总 storeStock主表的id 用于限制芯级数据
                                    var storeStockContentFirst = stockContent.Where(t => t.BomAnalysecontentId == collectBomManager.Id && t.ProductCodeId.Contains(collectBomManager.ModuleId.ToString()) && t.SendTimeId.Contains(collectBomManager.SendTimeId.ToString()));
                                    var storeStockId = storeStockContentFirst.Select(t => t.StoreStockId).Distinct();
                                    //查询芯级下的所有预配套数据
                                    var queryCollectMatingNumberAlys = from queryloadContent in collectBomMaterialsContentDtos.AsQueryable()
                                                                       join queryStoreStocks in queryStoreStockList on
                                                                     queryloadContent.MerialsId equals queryStoreStocks.MaterialsContentId
                                                                       join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == collectBomManager.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                       select queryStoreStockContents;
                                    //查询该部套下的所有配套数据
                                    var queryCollectMatingNumber = from queryloadContent in loadData
                                                                   join queryStoreStocks in queryStoreStockList on
                                                                     queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                   join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectBomManager.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                   where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                   select queryStoreStockContents;

                                    //计算芯级可用预配套数量 汇总芯级配套数据
                                    var queryyptListCount = from queryloadContent in loadListTwo
                                                            join queryStoreStocks in queryStoreStockList on
                                                              queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                            join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectBomManager.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                            where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                            select new StoreStockContent
                                                            {
                                                                ProductDrawingNo = queryStoreStockContents.ProductDrawingNo,
                                                                Module = queryStoreStockContents.Module,
                                                                WorkStepId = queryloadContent.WorkStepEntityId,
                                                                StoreStockId = queryStoreStocks.Id,
                                                                MaterialsContentId = queryStoreStocks.MaterialsContentId,
                                                                BomAnalysecontentId = queryStoreStockContents.BomAnalysecontentId
                                                            };
                                    //&& queryCollectMatingNumber != null && queryCollectMatingNumber.Count() > 0
                                    if (queryyptListCount != null && queryyptListCount.Count() > 0)
                                    {
                                        matingDetaillists = (from tempLoad in loadData
                                                             join tempStroeStocks in queryStoreStockList
                                                             on tempLoad.MaterialsContentId equals tempStroeStocks.MaterialsContentId
                                                             join storestocks in storeStockId on tempStroeStocks.Id equals storestocks
                                                             //join tempStockContent in _storeStockContentRepsitory.GetAll() on tempStroeStocks.Id equals tempStockContent.StoreStockId
                                                             join tempMaterial in queryMaterialsContent on tempStroeStocks.MaterialsContentId equals tempMaterial.Id
                                                                 into tm
                                                             from tmi in tm.DefaultIfEmpty()
                                                                 //join queryyptlistCount in queryyptListCount on storestocks == null?Guid.Empty: storestocks equals queryyptlistCount ==null?Guid.Empty: queryyptlistCount.StoreStockId
                                                                 //into qlc from ql in qlc.DefaultIfEmpty()
                                                             join tempNode in _materialsNodeRepository.GetAll() on tmi.MaterialsNodeId equals tempNode.Id
                                                             into tn
                                                             from tpn in tn.DefaultIfEmpty()
                                                                 //join tempSearch in queryyptList on tempLoad ==null? Guid.Empty: tempLoad.MaterialsContentId equals (tempSearch == null ? Guid.Empty : tempSearch.MaterialsContentId) into ca
                                                                 //from ts in ca.DefaultIfEmpty()
                                                             join tempSysCode in querySysCode on tmi.UnitId equals tempSysCode.Id
                                                                into sc
                                                             from cc in sc.DefaultIfEmpty()
                                                                 //where (ts == null ? Guid.Empty : ts.LoadDetailsId) == tempLoad.Id
                                                             orderby tempLoad.Sort
                                                             //where (ts==null?Guid.Empty:ts.LoadDetailsId) == tempLoad.Id
                                                             select new MatingDetaillist
                                                             {
                                                                 data = new MatingEditChildData()
                                                                 {
                                                                     Code = tmi == null ? "" : tmi.MaterialNo,//物料代码
                                                                     Module = tmi == null ? "" : tmi.Model,//规格
                                                                     StoreStockId = tempStroeStocks.Id,
                                                                     CollectId = collectBomManager.Id,
                                                                     Number = tempLoad.Number,//工艺用量
                                                                     PreSuiteStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectBomManager.Id),
                                                                     DeliveryStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.OutboundState == OutboundStates.出库),
                                                                     UsableMatingQuantityStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectBomManager.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id),
                                                                     //queryyptListCount.FirstOrDefault(t => t.StoreStockId == storestocks).Quantity)
                                                                     WorkStepId = tempLoad.WorkStepEntityId,
                                                                     SuiteStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                     LoadDetailsId = tempLoad.Id,
                                                                     // 
                                                                     //tempStroeStocks.PreSuiteStock - tempStroeStocks.SuiteStock != 0 说明存在可用的配套数量 有可能存在负数
                                                                     //- ts.Quantity
                                                                     //&& tempLoad.Number - (tempStroeStocks.PreSuiteStock - tempStroeStocks.SuiteStock)>0
                                                                     StarvingStock = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectBomManager.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= 0 ? 0 :
                                                         tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectBomManager.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                     MatingStatus = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) > 0 ? (int)AssortStatus.缺料 :
                                                         tempLoad.Number - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectBomManager.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) && queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) != 0 && tempLoad.Number > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? (int)AssortStatus.配套中 : tempLoad.Number == queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? (int)AssortStatus.已配套 : (int)AssortStatus.未配套,
                                                                     MatingStatusName = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) > 0 ? AssortStatus.缺料.ToString() :
                                                         tempLoad.Number - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectBomManager.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) && queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) != 0 && tempLoad.Number > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.配套中.ToString() : tempLoad.Number == queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.已配套.ToString() : "未配套",
                                                                     CompletePeople = tempStroeStocks.CompletePeople,
                                                                     CompleteTime = tempStroeStocks.CompleteTime.ToString(),
                                                                     PreSuiteName = tempStroeStocks.PreSuiteName,
                                                                     PreSuiteTime = tempStroeStocks.PreSuiteTime.ToString(),
                                                                     ProductNumber = tempStroeStocks.ProductNumber
                                                                 }
                                                             }).ToList();

                                        if (matingDetaillists != null && matingDetaillists.Count > 0)
                                        {
                                            var tempStore = (from tqy in loadData
                                                             join queryLoadData in matingDetaillists on tqy.Id equals queryLoadData.data.LoadDetailsId
                                                             into qld
                                                             from qlda in qld.DefaultIfEmpty()
                                                             select new MatingDetaillist
                                                             {
                                                                 data = new MatingEditChildData
                                                                 {
                                                                     HJXH = qlda == null ? "" : qlda.data.HJXH,
                                                                     HJFC = qlda == null ? "" : qlda.data.HJFC,
                                                                     CollectId = qlda == null ? Guid.Empty : qlda.data.CollectId,
                                                                     Code = qlda == null ? tqy.Code : qlda.data.Code,
                                                                     CompletePeople = qlda == null ? "" : qlda.data.CompletePeople,
                                                                     CompleteTime = qlda == null ? "" : qlda.data.CompleteTime,
                                                                     DeliveryStock = qlda == null ? 0 : qlda.data.DeliveryStock,
                                                                     Id = qlda == null ? Guid.Empty : qlda.data.Id,
                                                                     IsSuit = qlda == null ? 0 : qlda.data.IsSuit,
                                                                     JoinText = qlda == null ? "" : qlda.data.JoinText,
                                                                     LevelName = qlda == null ? "" : qlda.data.LevelName,
                                                                     LevelNum = qlda == null ? 0 : qlda.data.LevelNum,
                                                                     LoadDetailsId = qlda == null ? tqy.Id : qlda.data.LoadDetailsId,
                                                                     MaterialsNodeName = qlda == null ? "" : qlda.data.MaterialsNodeName,
                                                                     MaterialsTypeName = qlda == null ? "" : qlda.data.MaterialsTypeName,
                                                                     MatingStatus = qlda == null ? (int)AssortStatus.缺料 : qlda.data.MatingStatus,
                                                                     MatingStatusName = qlda == null ? "缺料" : qlda.data.MatingStatusName,
                                                                     Module = qlda == null ? "" : qlda.data.Module,
                                                                     Name = tqy.Name,
                                                                     NodeLevel = qlda == null ? 10 : qlda.data.NodeLevel,
                                                                     Number = qlda == null ? tqy.Number : qlda.data.Number,
                                                                     PreSuiteName = qlda == null ? "" : qlda.data.PreSuiteName,
                                                                     PreSuiteStock = qlda == null ? 0 : qlda.data.PreSuiteStock,
                                                                     PreSuiteTime = qlda == null ? "" : qlda.data.PreSuiteTime,
                                                                     ProductNumber = qlda == null ? "" : qlda.data.ProductNumber,
                                                                     StarvingStock = qlda == null ? 0 : qlda.data.StarvingStock,
                                                                     StoreStockId = qlda == null ? Guid.Empty : qlda.data.StoreStockId,
                                                                     SuiteStock = qlda == null ? 0 : qlda.data.SuiteStock,
                                                                     Unit = qlda == null ? "" : qlda.data.Unit,
                                                                     UsableMatingQuantityStock = qlda == null ? 0 : qlda.data.UsableMatingQuantityStock,
                                                                     UsableQuantityStock = qlda == null ? 0 : qlda.data.UsableQuantityStock,
                                                                     WorkStepId = qlda == null ? tqy.WorkStepEntityId : qlda.data.WorkStepId,
                                                                     XJName = qlda == null ? "" : qlda.data.XJName,
                                                                 }
                                                             }
                                                           ).ToList();
                                            foreach (MatingDetaillist matingDetaillist in tempStore)
                                            {
                                                var bs = matingDetaillists.Where(t => t.data.MatingStatus == (int)AssortStatus.缺料);

                                                if (bs != null && bs.Count() > 0)
                                                {
                                                    matingName = AssortStatus.缺料.ToString();
                                                    break;
                                                }
                                                if (matingDetaillist.data.MatingStatus == (int)AssortStatus.缺料)
                                                {
                                                    matingName = AssortStatus.缺料.ToString();
                                                    break;
                                                }
                                                else if (matingDetaillist.data.MatingStatus == (int)AssortStatus.配套中)
                                                {
                                                    matingName = AssortStatus.配套中.ToString();
                                                    break;
                                                }
                                                else if (matingDetaillist.data.MatingStatus == (int)AssortStatus.已配套)
                                                {
                                                    matingName = AssortStatus.已配套.ToString();
                                                    break;
                                                }
                                                else if (matingDetaillist.data.MatingStatus == (int)AssortStatus.未配套)
                                                {
                                                    matingName = AssortStatus.未配套.ToString();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    MatingTreeGridDto mating = new MatingTreeGridDto();
                                    MatingEditParentData temp = new MatingEditParentData();
                                    if (matingDetaillists.Count > 0)
                                    {
                                        //计算提取芯级预配套数量、可用预配套数量 进行去重
                                        var contentRequest = matingDetaillists.Select(x => new { x.data.Code, x.data.Module, x.data.PreSuiteStock, x.data.UsableMatingQuantityStock }).Distinct();
                                        //计算配套数量缺料数量的汇总

                                        var groupByBtContent = (from guoupAll in (from groupContent in (from queryStoreStock in matingDetaillists select queryStoreStock)
                                                                                  group groupContent by new { groupContent.data.CollectId, groupContent.data.Module, groupContent.data.Code } into gc
                                                                                  select new
                                                                                  {
                                                                                      PreSuiteStockAll = contentRequest.Where(t => t.Module == gc.Key.Module && t.Code == gc.Key.Code).Sum(t => t.PreSuiteStock),
                                                                                      UsableMatingQuantityStockAll = contentRequest.Where(t => t.Module == gc.Key.Module && t.Code == gc.Key.Code).Sum(t => t.UsableMatingQuantityStock),//可用预配套数量
                                                                                      SuiteStockAll = gc.Sum(t => t.data.SuiteStock),
                                                                                      StarvingStockAll = gc.Sum(t => t.data.StarvingStock),
                                                                                      DeliveryStockAll = gc.Sum(t => t.data.DeliveryStock),
                                                                                      CollectId = gc.Key.CollectId
                                                                                  })
                                                                group guoupAll by new { guoupAll.CollectId } into all
                                                                select new
                                                                {
                                                                    PreSuiteStockAll = all.Sum(t => t.PreSuiteStockAll),
                                                                    UsableMatingQuantityStockAll = all.Sum(t => t.UsableMatingQuantityStockAll),
                                                                    SuiteStockAll = all.Sum(t => t.SuiteStockAll),
                                                                    StarvingStockAll = all.Sum(t => t.StarvingStockAll),
                                                                    DeliveryStockAll = all.Sum(t => t.DeliveryStockAll)
                                                                }).FirstOrDefault();


                                        temp.Code = item.NodeDrawingNo;
                                        temp.Name = item.NodeName;
                                        temp.SuiteStock = SuiteStock;
                                        temp.MatingStatusName = matingName;
                                        //temp.OutboundedNum = OutboundedNum;
                                        //temp.OutboundQuantity = OutboundQuantity;
                                        //temp.ShortageNum = ShortageNum;
                                        //temp.AssortState = AssortState;
                                        Level++;
                                        temp.LevelName = Level.ToString();
                                        if (ProcessDosage > (groupByBtContent.UsableMatingQuantityStockAll + groupByBtContent.SuiteStockAll))
                                        {
                                            temp.MatingStatusName = AssortStatus.缺料.ToString();
                                            temp.StarvingStock = ProcessDosage - (groupByBtContent.UsableMatingQuantityStockAll + groupByBtContent.SuiteStockAll);
                                        }
                                        else
                                        {
                                            temp.MatingStatusName = matingName;
                                            temp.StarvingStock = groupByBtContent.StarvingStockAll;
                                        }
                                        temp.PreSuiteStock = groupByBtContent.PreSuiteStockAll;
                                        temp.Number = ProcessDosage;
                                        temp.UsableMatingQuantityStock = groupByBtContent.UsableMatingQuantityStockAll;
                                        temp.SuiteStock = groupByBtContent.SuiteStockAll;
                                        temp.DeliveryStock = groupByBtContent.DeliveryStockAll;
                                        mating.data = temp;
                                        outputs.Add(mating);
                                    }
                                    else
                                    {
                                        temp.Code = item.NodeDrawingNo;
                                        temp.Name = item.NodeName;
                                        temp.SuiteStock = SuiteStock;
                                        temp.MatingStatusName = matingName;

                                        temp.MatingStatusName = AssortStatus.缺料.ToString();
                                        temp.StarvingStock = 0;
                                        temp.PreSuiteStock = 0;
                                        temp.Number = ProcessDosage;
                                        temp.UsableMatingQuantityStock = 0;
                                        temp.SuiteStock = 0;
                                        temp.DeliveryStock = 0;
                                        Level++;
                                        temp.LevelName = Level.ToString();
                                        mating.data = temp;
                                        outputs.Add(mating);
                                    }


                                }
                            }
                        }
                        break;
                    case 3:
                        int techPreSuiteStock = 0;
                        int suiteStockAll = 0;
                        var bopNode = _bopNodeRepository.Get(input.NodeId);
                        var techId = bopNode.TechniqueEntityId;
                        var proTemp = _processesEntityRepository.GetAll().Where(d => d.TechniqueEntityId == techId).OrderBy(d => d.ProcessesSequence).ToList();

                        var coreGradeNode = _bopNodeRepository.GetAll().Where(d => d.NodeCode == bopNode.ParentCode.Substring(0, 3) && d.ParentId == bopNode.BopDescId).FirstOrDefault();
                        if (coreGradeNode == null)
                        {
                            return new MatingTreeResult();
                            //throw new UserFriendlyException("未找到该节点对应的芯级!");
                            //var totalMaterial = _bomAnalyseAppServiceRepository.GetExternalCall(coreGradeNode.NodeName, coreGradeNode.NodeDrawingNo, bopDesc.ModelId, bopDesc.LotNoId);
                        }
                        var bopDesc = _bopDescRepository.Get(coreGradeNode.BopDescId);
                        //找出所有的规程  （找到所有规程 能找到所有的装入件、contains）
                        var techQueryThree = _bopNodeRepository.GetAll().Where(d => d.ParentCode.StartsWith(coreGradeNode.NodeCode) && d.BopDescId == coreGradeNode.BopDescId).Where(d => d.TechniqueEntityId != null).Select(d => d.TechniqueEntityId).ToList();
                        var workIdsThreeAll = queryWorkStepEntity.Where(d => techQueryThree.Contains(d.TechniqueEntityId)).Select(d => d.Id);
                        //找出所有的装入件
                        var loadListThree = (from cc in loadQuery
                                             join mm in workIdsThreeAll on cc.WorkStepEntityId equals mm
                                             select cc).ToList();
                        if (proTemp.Count > 0)
                        {
                            foreach (var item in proTemp)
                            {
                                int ProcessDosage = 0;
                                string matingName = "";
                                var workIdsThree = queryWorkStepEntity.Where(d => d.ProcessesEntityId == item.Id).Select(d => d.Id);
                                if (workIdsThree.Count() > 0)
                                {
                                    var loadData = (from loadPieceList in loadQuery.Where(d => workIdsThree.Contains(d.WorkStepEntityId)).ToList().OrderBy(d => d.Sort)
                                                   join materialsList in queryMaterialsContent on loadPieceList.MaterialsContentId equals materialsList.Id
                                                   select loadPieceList).ToList();

                                    if (loadData.Count > 0)
                                    {
                                        ProcessDosage = (from loadPieceList in loadQuery.Where(d => workIdsThree.Contains(d.WorkStepEntityId)) select loadPieceList).Sum(t => t.Number);
                                        var collectContent = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.XJName == coreGradeNode.NodeName && t.XJDrawingNo == coreGradeNode.NodeDrawingNo && t.ModuleId == bopDesc.ModelId && t.SendTimeId == bopDesc.LotNoId).Result;
                                        if (collectContent != null)
                                        {
                                            var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectContent.XJId);
                                            if (collectBomMaterialsContentDtos == null)
                                            {
                                                result.Message = "该芯级下没有汇总数据，请检查";
                                                result.code = 1;
                                                return result;
                                            }
                                            var storeStockContentFirst = stockContent.Where(t => t.BomAnalysecontentId == collectContent.Id && t.ProductCodeId.Contains(collectContent.ModuleId.ToString()) && t.SendTimeId.Contains(collectContent.SendTimeId.ToString()));
                                            var storeStockId = storeStockContentFirst.Select(t => t.StoreStockId).Distinct();
                                            //查询芯级下的所有预配套数据
                                            var queryCollectMatingNumberAlys = from queryloadContent in collectBomMaterialsContentDtos
                                                                               join queryStoreStocks in queryStoreStockList on
                                                                             queryloadContent.MerialsId equals queryStoreStocks.MaterialsContentId
                                                                               join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                               select queryStoreStockContents;
                                            //查询芯级下的所有配套数据
                                            var queryCollectMatingNumber = from queryloadContent in loadData
                                                                           join queryStoreStocks in queryStoreStockList on
                                                                             queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                           join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                           where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                           select queryStoreStockContents;

                                            //汇总可预配套数量 汇总配套数据
                                            var queryyptListCount = from queryloadContent in loadListThree
                                                                    join queryStoreStocks in queryStoreStockList on
                                                                      queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                    join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                    where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                    select new StoreStockContent
                                                                    {
                                                                        ProductDrawingNo = queryStoreStockContents.ProductDrawingNo,
                                                                        Module = queryStoreStockContents.Module,
                                                                        WorkStepId = queryloadContent.WorkStepEntityId,
                                                                        StoreStockId = queryStoreStocks.Id,
                                                                        MaterialsContentId = queryStoreStocks.MaterialsContentId,
                                                                        BomAnalysecontentId = queryStoreStockContents.BomAnalysecontentId
                                                                    };
                                            //if (queryyptList != null && queryyptList .Count()>0&& queryCollectMatingNumber != null&& queryCollectMatingNumber.Count()>0)
                                            //{
                                            var storeStorkContent = (from tempLoad in loadData
                                                                     join tempStroeStocks in queryStoreStockList
                                                                     on tempLoad.MaterialsContentId equals tempStroeStocks.MaterialsContentId
                                                                     join storestocks in storeStockId on tempStroeStocks.Id equals storestocks
                                                                     //join tempStockContent in _storeStockContentRepsitory.GetAll() on tempStroeStocks.Id equals tempStockContent.StoreStockId
                                                                     join tempMaterial in queryMaterialsContent on tempStroeStocks.MaterialsContentId equals tempMaterial.Id
                                                                         into tm
                                                                     from tmi in tm.DefaultIfEmpty()
                                                                         //join queryyptlistCount in queryyptListCount on storestocks == null?Guid.Empty: storestocks equals queryyptlistCount ==null?Guid.Empty: queryyptlistCount.StoreStockId
                                                                         //into qlc from ql in qlc.DefaultIfEmpty()
                                                                     join tempNode in _materialsNodeRepository.GetAll() on tmi.MaterialsNodeId equals tempNode.Id
                                                                     into tn
                                                                     from tpn in tn.DefaultIfEmpty()
                                                                         //join tempSearch in queryyptList on tempLoad ==null? Guid.Empty: tempLoad.MaterialsContentId equals (tempSearch == null ? Guid.Empty : tempSearch.MaterialsContentId) into ca
                                                                         //from ts in ca.DefaultIfEmpty()
                                                                     join tempSysCode in querySysCode on tmi.UnitId equals tempSysCode.Id
                                                                        into sc
                                                                     from cc in sc.DefaultIfEmpty()
                                                                         //where (ts == null ? Guid.Empty : ts.LoadDetailsId) == tempLoad.Id
                                                                     orderby tempLoad.Sort
                                                                     //where (ts==null?Guid.Empty:ts.LoadDetailsId) == tempLoad.Id
                                                                     orderby tempLoad.Sort
                                                                     select new MatingDetaillist
                                                                     {
                                                                         data = new MatingEditChildData()
                                                                         {
                                                                             Code = tmi == null ? "" : tmi.MaterialNo,//物料代码
                                                                             Module = tmi == null ? "" : tmi.Model,//规格
                                                                             StoreStockId = tempStroeStocks.Id,
                                                                             CollectId = collectContent.Id,
                                                                             Number = tempLoad.Number,//工艺用量
                                                                             PreSuiteStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id),
                                                                             DeliveryStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.OutboundState == OutboundStates.出库),
                                                                             UsableMatingQuantityStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id),
                                                                             //queryyptListCount.FirstOrDefault(t => t.StoreStockId == storestocks).Quantity)
                                                                             WorkStepId = tempLoad.WorkStepEntityId,
                                                                             SuiteStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                             LoadDetailsId = tempLoad.Id,
                                                                             // 
                                                                             //tempStroeStocks.PreSuiteStock - tempStroeStocks.SuiteStock != 0 说明存在可用的配套数量 有可能存在负数
                                                                             //- ts.Quantity
                                                                             //&& tempLoad.Number - (tempStroeStocks.PreSuiteStock - tempStroeStocks.SuiteStock)>0
                                                                             StarvingStock = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= 0 ? 0 :
                                                                 tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                             MatingStatus = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) > 0 ? (int)AssortStatus.缺料 :
                                                                 tempLoad.Number - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) && queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) != 0 && tempLoad.Number > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? (int)AssortStatus.配套中 : tempLoad.Number == queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? (int)AssortStatus.已配套 : (int)AssortStatus.未配套,
                                                                             MatingStatusName = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) > 0 ? AssortStatus.缺料.ToString() :
                                                                 tempLoad.Number - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) && queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) != 0 && tempLoad.Number > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.配套中.ToString() : tempLoad.Number == queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.已配套.ToString() : "未配套",
                                                                             CompletePeople = tempStroeStocks.CompletePeople,
                                                                             CompleteTime = tempStroeStocks.CompleteTime.ToString(),
                                                                             PreSuiteName = tempStroeStocks.PreSuiteName,
                                                                             PreSuiteTime = tempStroeStocks.PreSuiteTime.ToString(),
                                                                             ProductNumber = tempStroeStocks.ProductNumber
                                                                         }
                                                                     }).ToList();

                                            if (storeStorkContent != null && storeStorkContent.Count > 0)
                                            {
                                                var tempStore = (from tqy in loadData
                                                                 join queryLoadData in storeStorkContent on tqy.Id equals queryLoadData.data.LoadDetailsId
                                                                 into qld
                                                                 from qlda in qld.DefaultIfEmpty()
                                                                 select new MatingDetaillist
                                                                 {
                                                                     data = new MatingEditChildData
                                                                     {
                                                                         HJXH = qlda == null ? "" : qlda.data.HJXH,
                                                                         HJFC = qlda == null ? "" : qlda.data.HJFC,
                                                                         CollectId = qlda == null ? Guid.Empty : qlda.data.CollectId,
                                                                         Code = qlda == null ? tqy.Code : qlda.data.Code,
                                                                         CompletePeople = qlda == null ? "" : qlda.data.CompletePeople,
                                                                         CompleteTime = qlda == null ? "" : qlda.data.CompleteTime,
                                                                         DeliveryStock = qlda == null ? 0 : qlda.data.DeliveryStock,
                                                                         Id = qlda == null ? Guid.Empty : qlda.data.Id,
                                                                         IsSuit = qlda == null ? 0 : qlda.data.IsSuit,
                                                                         JoinText = qlda == null ? "" : qlda.data.JoinText,
                                                                         LevelName = qlda == null ? "" : qlda.data.LevelName,
                                                                         LevelNum = qlda == null ? 0 : qlda.data.LevelNum,
                                                                         LoadDetailsId = qlda == null ? tqy.Id : qlda.data.LoadDetailsId,
                                                                         MaterialsNodeName = qlda == null ? "" : qlda.data.MaterialsNodeName,
                                                                         MaterialsTypeName = qlda == null ? "" : qlda.data.MaterialsTypeName,
                                                                         MatingStatus = qlda == null ? (int)AssortStatus.缺料 : qlda.data.MatingStatus,
                                                                         MatingStatusName = qlda == null ? "缺料" : qlda.data.MatingStatusName,
                                                                         Module = qlda == null ? "" : qlda.data.Module,
                                                                         Name = tqy.Name,
                                                                         NodeLevel = qlda == null ? 10 : qlda.data.NodeLevel,
                                                                         Number = qlda == null ? tqy.Number : qlda.data.Number,
                                                                         PreSuiteName = qlda == null ? "" : qlda.data.PreSuiteName,
                                                                         PreSuiteStock = qlda == null ? 0 : qlda.data.PreSuiteStock,
                                                                         PreSuiteTime = qlda == null ? "" : qlda.data.PreSuiteTime,
                                                                         ProductNumber = qlda == null ? "" : qlda.data.ProductNumber,
                                                                         StarvingStock = qlda == null ? 0 : qlda.data.StarvingStock,
                                                                         StoreStockId = qlda == null ? Guid.Empty : qlda.data.StoreStockId,
                                                                         SuiteStock = qlda == null ? 0 : qlda.data.SuiteStock,
                                                                         Unit = qlda == null ? "" : qlda.data.Unit,
                                                                         UsableMatingQuantityStock = qlda == null ? 0 : qlda.data.UsableMatingQuantityStock,
                                                                         UsableQuantityStock = qlda == null ? 0 : qlda.data.UsableQuantityStock,
                                                                         WorkStepId = qlda == null ? tqy.WorkStepEntityId : qlda.data.WorkStepId,
                                                                         XJName = qlda == null ? "" : qlda.data.XJName,
                                                                     }
                                                                 }
                                                               ).ToList();
                                                foreach (MatingDetaillist matingDetaillist in tempStore)
                                                {
                                                    var bs = storeStorkContent.Where(t => t.data.MatingStatus == (int)AssortStatus.缺料);

                                                    if (bs != null && bs.Count() > 0)
                                                    {
                                                        matingName = AssortStatus.缺料.ToString();
                                                        break;
                                                    }
                                                    if (matingDetaillist.data.MatingStatus == (int)AssortStatus.缺料)
                                                    {
                                                        matingName = AssortStatus.缺料.ToString();
                                                        break;
                                                    }
                                                    else if (matingDetaillist.data.MatingStatus == (int)AssortStatus.配套中)
                                                    {
                                                        matingName = AssortStatus.配套中.ToString();
                                                        break;
                                                    }
                                                    else if (matingDetaillist.data.MatingStatus == (int)AssortStatus.已配套)
                                                    {
                                                        matingName = AssortStatus.已配套.ToString();
                                                        break;
                                                    }
                                                    else if (matingDetaillist.data.MatingStatus == (int)AssortStatus.未配套)
                                                    {
                                                        matingName = AssortStatus.未配套.ToString();
                                                        break;
                                                    }
                                                }
                                            }
                                            //计算提取芯级预配套数量、可用预配套数量 进行去重
                                            var contentRequest = storeStorkContent.ToList().Select(x => new { x.data.Code, x.data.Module, x.data.PreSuiteStock, x.data.UsableMatingQuantityStock }).Distinct();

                                            //计算配套数量缺料数量的汇总
                                            var groupByBtContent = (from guoupAll in (from groupContent in (from queryStoreStock in storeStorkContent select queryStoreStock)
                                                                                      group groupContent by new { groupContent.data.CollectId, groupContent.data.Module, groupContent.data.Code } into gc
                                                                                      select new
                                                                                      {
                                                                                          PreSuiteStockAll = contentRequest.Where(t => t.Module == gc.Key.Module && t.Code == gc.Key.Code).Sum(t => t.PreSuiteStock),
                                                                                          UsableMatingQuantityStockAll = contentRequest.Where(t => t.Module == gc.Key.Module && t.Code == gc.Key.Code).Sum(t => t.UsableMatingQuantityStock),//可用预配套数量
                                                                                          SuiteStockAll = gc.Sum(t => t.data.SuiteStock),
                                                                                          StarvingStockAll = gc.Sum(t => t.data.StarvingStock),
                                                                                          DeliveryStockAll = gc.Sum(t => t.data.DeliveryStock),
                                                                                          CollectId = gc.Key.CollectId
                                                                                      })
                                                                    group guoupAll by new { guoupAll.CollectId } into all
                                                                    select new
                                                                    {
                                                                        PreSuiteStockAll = all.Sum(t => t.PreSuiteStockAll),
                                                                        UsableMatingQuantityStockAll = all.Sum(t => t.UsableMatingQuantityStockAll),
                                                                        SuiteStockAll = all.Sum(t => t.SuiteStockAll),
                                                                        StarvingStockAll = all.Sum(t => t.StarvingStockAll),
                                                                        DeliveryStockAll = all.Sum(t => t.DeliveryStockAll)
                                                                    }).FirstOrDefault();

                                            MatingTreeGridDto mating = new MatingTreeGridDto();
                                            MatingEditParentData matingpd = new MatingEditParentData();
                                            matingpd.Code = "工序" + item.ProcessesSequence.ToString() + " "; ;
                                            matingpd.Name = item.ProcessesName;
                                            matingpd.Id = item.Id;
                                            matingpd.JoinText = "工序";
                                            matingpd.NodeLevel = 8;
                                            Level++;
                                            matingpd.LevelName = Level.ToString();
                                            if (groupByBtContent != null)
                                            {
                                                if (ProcessDosage > (groupByBtContent.UsableMatingQuantityStockAll + groupByBtContent.SuiteStockAll))
                                                {
                                                    matingpd.MatingStatusName = AssortStatus.缺料.ToString();
                                                    matingpd.StarvingStock = ProcessDosage - (groupByBtContent.UsableMatingQuantityStockAll + groupByBtContent.SuiteStockAll);
                                                    matingpd.PreSuiteStock = groupByBtContent.PreSuiteStockAll;
                                                }
                                                else
                                                {
                                                    matingpd.MatingStatusName = matingName;
                                                    matingpd.StarvingStock = groupByBtContent.StarvingStockAll;
                                                }
                                                matingpd.UsableMatingQuantityStock = groupByBtContent.UsableMatingQuantityStockAll;
                                                matingpd.SuiteStock = groupByBtContent.SuiteStockAll;
                                                matingpd.DeliveryStock = groupByBtContent.DeliveryStockAll;
                                            }

                                            matingpd.Number = ProcessDosage;
                                            mating.data = matingpd;
                                            outputs.Add(mating);
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    case 4:
                        var proceTemp = _processesEntityRepository.Get(input.NodeId);
                        int numberCount = 0;
                        string xjcode = "";
                        string xjName = "";





                        //获取工序下的所有工步
                        var workTemp = queryWorkStepEntity.Where(d => d.ProcessesEntityId == input.NodeId).OrderBy(d => d.WorkStepNumber).ToList();
                        if (workTemp.Count > 0)
                        {
                            var coreNodeInputList = (from temp in _bopNodeRepository.GetAll().Where(d => d.TechniqueEntityId == proceTemp.TechniqueEntityId)
                                                     select new
                                                     {
                                                         ParentCode = temp.ParentCode.Substring(0, 3),
                                                         BopDescId = temp.BopDescId
                                                     }).FirstOrDefault();
                            //型号发次
                            var moduleLotNo = _bopDescRepository.FirstOrDefaultAsync(t => t.Id == coreNodeInputList.BopDescId).Result;

                            if (coreNodeInputList != null)
                            {
                                var coreNode = _bopNodeRepository.GetAll().Where(d => d.NodeCode == coreNodeInputList.ParentCode && d.ParentId == coreNodeInputList.BopDescId).FirstOrDefault();
                                if (coreNode != null)
                                {
                                    xjcode = coreNode.NodeDrawingNo;
                                    xjName = coreNode.NodeName;
                                }
                                //找出所有的规程  （找到所有规程 能找到所有的装入件、contains）
                                var techQuery = _bopNodeRepository.GetAll().Where(d => d.NodeCode.StartsWith(coreNode.NodeCode) && d.BopDescId == coreNode.BopDescId).Where(d => d.TechniqueEntityId != null).Select(d => d.TechniqueEntityId).ToList();
                                var workIds = queryWorkStepEntity.Where(d => techQuery.Contains(d.TechniqueEntityId)).Select(d => d.Id);
                                //找出所有的装入件
                                var loadList = (from cc in loadQuery
                                                join mm in workIds on cc.WorkStepEntityId equals mm
                                                select cc).ToList();
                                //找出所有工步的id
                                var workIdList = workTemp.Select(d => d.Id).ToList();
                                //根据工步获取装入件明细 所有工步下的装入件明细

                                //var lo = _loadPieceRepository.GetAll().Where(d => workIdList.Contains(d.WorkStepEntityId)).OrderBy(d => d.Sort);

                                var loadData = (from loadPieceList in loadQuery.Where(d => workIdList.Contains(d.WorkStepEntityId)).OrderBy(d => d.Sort)
                                                join materialsList in queryMaterialsContent on loadPieceList.MaterialsContentId equals materialsList.Id
                                                into mll
                                                from ml in mll.DefaultIfEmpty()
                                                select loadPieceList).ToList();

                                ////获取可用预配套数量
                                //var storeStocksContent = from queryMaterislsContent in _materialsContentRepository.GetAll()
                                //                         join queryStoreStocks in _storeStockRepsitory.GetAll() on
                                //                         queryMaterislsContent.Id equals queryStoreStocks.MaterialsContentId
                                //                         join queryStoreStockContents in _storeStockContentRepsitory.GetAll().
                                //                         Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是&&t.BomAnalysecontentId != null&&t.LoadDetailsId==null&&t.IsSuit  == IsSuits.否) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                //                         join queryloadData in loadData on queryMaterislsContent.Id equals queryloadData.MaterialsContentId
                                //                         select queryStoreStockContents;
                                //找出预配套的数量
                                List<MatingDetaillist> tempQuery = new List<MatingDetaillist>();

                                if (loadData.Count() > 0)
                                {
                                    var collectContent = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.XJName == xjName && t.XJDrawingNo == xjcode && t.ModuleId == moduleLotNo.ModelId && t.SendTimeId == moduleLotNo.LotNoId).Result;
                                    if (collectContent != null)
                                    {
                                        //throw new UserFriendlyException("该节点下没有对应的芯级");

                                        var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectContent.XJId);
                                        if (collectBomMaterialsContentDtos == null || collectContent == null)
                                        {
                                            result.Message = "该芯级下没有汇总数据，请检查";
                                            result.code = 1;
                                            return result;
                                        }
                                        var storeStockContentFirst = stockContent.Where(t => t.BomAnalysecontentId == collectContent.Id && (t.ProductCodeId.Contains(collectContent.ModuleId.ToString()) && t.SendTimeId.Contains(collectContent.SendTimeId.ToString()))|| t.ProductCode.Contains(moduleLotNo.Model + "系列"));
                                        var storeStockId = storeStockContentFirst.Select(t => t.StoreStockId).Distinct();
                                        //查询芯级下的所有预配套数据
                                        var queryCollectMatingNumberAlys = from queryloadContent in collectBomMaterialsContentDtos.AsQueryable()
                                                                           join queryStoreStocks in queryStoreStockList on
                                                                         queryloadContent.MerialsId equals queryStoreStocks.MaterialsContentId
                                                                           join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                           select queryStoreStockContents;
                                        //查询芯级下的所有配套数据
                                        var queryCollectMatingNumber = from queryloadContent in loadData
                                                                       join queryStoreStocks in queryStoreStockList on
                                                                         queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                       join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                       where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                       select queryStoreStockContents;

                                        //汇总可预配套数量 汇总配套数据
                                        var queryyptListCount = from queryloadContent in loadList
                                                                join queryStoreStocks in queryStoreStockList on
                                                                  queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                select new StoreStockContent
                                                                {
                                                                    ProductDrawingNo = queryStoreStockContents.ProductDrawingNo,
                                                                    Module = queryStoreStockContents.Module,
                                                                    WorkStepId = queryloadContent.WorkStepEntityId,
                                                                    StoreStockId = queryStoreStocks.Id,
                                                                    MaterialsContentId = queryStoreStocks.MaterialsContentId,
                                                                    BomAnalysecontentId = queryStoreStockContents.BomAnalysecontentId
                                                                };
                                        try
                                        {
                                            tempQuery = (from tempLoad in loadData
                                                         join tempStroeStocks in queryStoreStockList
                                                         on tempLoad.MaterialsContentId equals tempStroeStocks.MaterialsContentId
                                                         join storestocks in storeStockId on tempStroeStocks.Id equals storestocks
                                                         //join tempStockContent in _storeStockContentRepsitory.GetAll() on tempStroeStocks.Id equals tempStockContent.StoreStockId
                                                         join tempMaterial in queryMaterialsContent on tempStroeStocks.MaterialsContentId equals tempMaterial.Id
                                                             into tm
                                                         from tmi in tm.DefaultIfEmpty()
                                                             //join queryyptlistCount in queryyptListCount on storestocks == null?Guid.Empty: storestocks equals queryyptlistCount ==null?Guid.Empty: queryyptlistCount.StoreStockId
                                                             //into qlc from ql in qlc.DefaultIfEmpty()
                                                         join tempNode in _materialsNodeRepository.GetAll() on tmi.MaterialsNodeId equals tempNode.Id
                                                         into tn
                                                         from tpn in tn.DefaultIfEmpty()
                                                             //join tempSearch in queryyptList on tempLoad ==null? Guid.Empty: tempLoad.MaterialsContentId equals (tempSearch == null ? Guid.Empty : tempSearch.MaterialsContentId) into ca
                                                             //from ts in ca.DefaultIfEmpty()
                                                         join tempSysCode in querySysCode on tmi.UnitId equals tempSysCode.Id
                                                            into sc
                                                         from cc in sc.DefaultIfEmpty()
                                                             //where (ts == null ? Guid.Empty : ts.LoadDetailsId) == tempLoad.Id
                                                         orderby tempLoad.Sort
                                                         select new MatingDetaillist
                                                         {
                                                             data = new MatingEditChildData()
                                                             {
                                                                 HJFC = collectContent.SendTimeId.ToString(),
                                                                 HJXH = collectContent.ModuleId.ToString(),
                                                                 StoreStockId = tempStroeStocks.Id,
                                                                 Id = Guid.NewGuid(),
                                                                 CollectId = collectContent.Id,
                                                                 LoadDetailsId = tempLoad.Id,
                                                                 MaterialsTypeName = tpn == null ? "" : tpn.MaterialTypeName,//物料类别s
                                                                 Name = tempLoad.Name,// 物料名称
                                                                 Code = tmi == null ? "" : tempLoad.Code,//物料代码
                                                                 Module = tmi == null ? "" : tmi.Model,//规格
                                                                 Unit = cc == null ? "" : cc.Description,//单位
                                                                 Number = tempLoad.Number,//工艺用量
                                                                 MaterialsNodeName = tpn == null ? "" : tpn.MaterialTypeName,
                                                                 PreSuiteStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id),
                                                                 UsableMatingQuantityStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id),
                                                                 //queryyptListCount.FirstOrDefault(t => t.StoreStockId == storestocks).Quantity)
                                                                 WorkStepId = tempLoad.WorkStepEntityId,
                                                                 SuiteStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                 DeliveryStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.OutboundState == OutboundStates.出库),
                                                                 StarvingStock = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= 0 ? 0 :
                                                                 tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                 MatingStatus = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) > 0 ? (int)AssortStatus.缺料 :
                                                                 tempLoad.Number - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) && queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) != 0 && tempLoad.Number > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? (int)AssortStatus.配套中 : tempLoad.Number == queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? (int)AssortStatus.已配套 : (int)AssortStatus.未配套,
                                                                 MatingStatusName = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) > 0 ? AssortStatus.缺料.ToString() :
                                                                 tempLoad.Number - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) && queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) != 0 && tempLoad.Number > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.配套中.ToString() : tempLoad.Number == queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.已配套.ToString() : "未配套",
                                                                 CompletePeople = queryCollectMatingNumber.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null) != null ? queryCollectMatingNumber.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null).CompletePeople : "",
                                                                 CompleteTime = queryCollectMatingNumber.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null) != null ? queryCollectMatingNumber.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null).CompleteTime.ToString() : "",
                                                                 PreSuiteName = queryCollectMatingNumberAlys.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) != null ? queryCollectMatingNumberAlys.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id).PreSuiteName : "",
                                                                 PreSuiteTime = queryCollectMatingNumberAlys.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) != null ? queryCollectMatingNumberAlys.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id).PreSuiteTime.ToString() : "",
                                                                 ProductNumber = tempStroeStocks.ProductNumber,
                                                                 NodeLevel = 10
                                                             }
                                                         }).ToList();
                                            //循环工步id
                                            for (int i = 0; i < workIdList.Count; i++)
                                            {
                                                //
                                                var work = workTemp.Where(d => d.Id == workIdList[i]).First();
                                                MatingTreeGridDto mating = new MatingTreeGridDto();
                                                MatingEditParentData matingpd = new MatingEditParentData();
                                                //工步id
                                                matingpd.Id = work.Id;
                                                matingpd.Code = "工步" + proceTemp.ProcessesSequence.ToString() + "-" + work.WorkStepNumber.ToString();
                                                matingpd.Name = work.WorkStepNumber.ToString();
                                                matingpd.JoinText = "工步";
                                                matingpd.LevelName = (i + 1).ToString();
                                                mating.data = matingpd;
                                                mating.data.NodeLevel = 9;
                                                //matingpd.MatingStatusName = "缺料";
                                                //根据每个工步id 过滤出装入件明细
                                                var query = loadData.Where(d => d.WorkStepEntityId == workIdList[i]).ToList();


                                                if (query.Count > 0)
                                                {
                                                    //找出对应的配套数量
                                                    var tempStore = (from tqy in query
                                                                     join materContent in queryMaterialsContent on tqy.MaterialsContentId equals materContent.Id
                                               into mc
                                                                     from msd in mc.DefaultIfEmpty()
                                                                     join queryLoadData in tempQuery on tqy.Id equals tempQuery.Count == 0 ? Guid.Empty : queryLoadData.data.LoadDetailsId
                                                              into qld
                                                                     from qlda in qld.DefaultIfEmpty()
                                                                     join materNode in _materialsNodeRepository.GetAll() on msd == null ? Guid.Empty : msd.MaterialsNodeId equals materNode.Id into mn
                                                                     from mnd in mn.DefaultIfEmpty()
                                                                     join sysCode in querySysCode on msd == null ? Guid.Empty : msd.UnitId equals sysCode.Id
                                                                     into syc
                                                                     from sy in syc.DefaultIfEmpty()

                                                                     select new MatingDetaillist
                                                                     {
                                                                         data = new MatingEditChildData
                                                                         {
                                                                             HJXH = qlda == null ? "" : qlda.data.HJXH,
                                                                             HJFC = qlda == null ? "" : qlda.data.HJFC,
                                                                             CollectId = qlda == null ? Guid.Empty : qlda.data.CollectId,
                                                                             Code = qlda == null ? _storeFunctionsAppService.GetStandardDrawingNoDispose(tqy.Code).ProductDrawingNo : _storeFunctionsAppService.GetStandardDrawingNoDispose(qlda.data.Code).ProductDrawingNo,
                                                                             CompletePeople = qlda == null ? "" : qlda.data.CompletePeople,
                                                                             CompleteTime = qlda == null ? "" : qlda.data.CompleteTime,
                                                                             DeliveryStock = qlda == null ? 0 : qlda.data.DeliveryStock,
                                                                             Id = qlda == null ? Guid.Empty : qlda.data.Id,
                                                                             IsSuit = qlda == null ? 0 : qlda.data.IsSuit,
                                                                             JoinText = qlda == null ? "" : qlda.data.JoinText,
                                                                             LevelName = qlda == null ? "" : qlda.data.LevelName,
                                                                             LevelNum = qlda == null ? 0 : qlda.data.LevelNum,
                                                                             LoadDetailsId = qlda == null ? tqy.Id : qlda.data.LoadDetailsId,
                                                                             MaterialsNodeName = qlda == null ? mnd == null ? "" : mnd.MaterialTypeName : qlda.data.MaterialsNodeName,
                                                                             MaterialsTypeName = qlda == null ? mnd == null ? "" : mnd.MaterialTypeName : qlda.data.MaterialsTypeName,
                                                                             MatingStatus = qlda == null ? (int)AssortStatus.缺料 : qlda.data.MatingStatus,
                                                                             MatingStatusName = qlda == null ? "缺料" : qlda.data.MatingStatusName,
                                                                             Module = qlda == null ? _storeFunctionsAppService.GetStandardDrawingNoDispose(tqy.Code).Module : _storeFunctionsAppService.GetStandardDrawingNoDispose(qlda.data.Code).Module,
                                                                             Name = tqy.Name,
                                                                             NodeLevel = qlda == null ? 10 : qlda.data.NodeLevel,
                                                                             Number = qlda == null ? tqy.Number : qlda.data.Number,
                                                                             PreSuiteName = qlda == null ? "" : qlda.data.PreSuiteName,
                                                                             PreSuiteStock = qlda == null ? 0 : qlda.data.PreSuiteStock,
                                                                             PreSuiteTime = qlda == null ? "" : qlda.data.PreSuiteTime,
                                                                             ProductNumber = qlda == null ? "" : qlda.data.ProductNumber,
                                                                             StarvingStock = qlda == null ? 0 : qlda.data.StarvingStock,
                                                                             StoreStockId = qlda == null ? Guid.Empty : qlda.data.StoreStockId,
                                                                             SuiteStock = qlda == null ? 0 : qlda.data.SuiteStock,
                                                                             Unit = qlda == null ? sy == null ? "" : sy.Description : qlda.data.Unit,
                                                                             UsableMatingQuantityStock = qlda == null ? 0 : qlda.data.UsableMatingQuantityStock,
                                                                             UsableQuantityStock = qlda == null ? 0 : qlda.data.UsableQuantityStock,
                                                                             WorkStepId = qlda == null ? tqy.WorkStepEntityId : qlda.data.WorkStepId,
                                                                             XJName = qlda == null ? "" : qlda.data.XJName,
                                                                             YearsNo = qlda == null ? _storeFunctionsAppService.GetStandardDrawingNoDispose(tqy.Code).YearNo : _storeFunctionsAppService.GetStandardDrawingNoDispose(qlda.data.Code).YearNo
                                                                         }
                                                                     }
                                                                    ).ToList();
                                                    if (tempStore.Count > 0)
                                                    {
                                                        for (int j = 0; j < tempStore.Count(); j++)
                                                        {
                                                            if (tempStore[j] != null)
                                                            {
                                                                tempStore[j].data.LevelName = matingpd.LevelName + "." + (j + 1).ToString();
                                                            }
                                                        }
                                                    }

                                                    mating.children = tempStore;
                                                }
                                                outputs.Add(mating);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            throw;
                                        }

                                    }
                                }

                            }
                        }
                        break;
                    case 5:
                        var workStep = queryWorkStepEntity.FirstOrDefault(d => d.Id == input.NodeId);

                        string xjcodeFive = "";
                        string xjNameFive = "";
                        if (workStep != null)
                        {

                            var workStepInput = (from temp in _bopNodeRepository.GetAll().Where(d => d.TechniqueEntityId == workStep.TechniqueEntityId)
                                                 select new
                                                 {
                                                     ParentCode = temp.ParentCode.Substring(0, 3),
                                                     BopDescId = temp.BopDescId
                                                 }).FirstOrDefault();
                            if (workStepInput != null)
                            {
                                var coreNode = _bopNodeRepository.GetAll().Where(d => d.NodeCode == workStepInput.ParentCode && d.BopDescId == workStepInput.BopDescId).FirstOrDefault();
                                if (coreNode != null)
                                {
                                    xjNameFive = coreNode.NodeName;
                                    xjcodeFive = coreNode.NodeDrawingNo;
                                }
                                var techQuery = _bopNodeRepository.GetAll().Where(d => d.NodeCode.StartsWith(coreNode.NodeCode) && d.BopDescId == coreNode.BopDescId).Where(d => d.TechniqueEntityId != null).Select(d => d.TechniqueEntityId).ToList();
                                if (techQuery.Count > 0)
                                {
                                    var workIds = queryWorkStepEntity.Where(d => techQuery.Contains(d.TechniqueEntityId)).Select(d => d.Id);

                                    //获取或有的装入件
                                    var loadList = from cc in loadQuery
                                                   join mm in workIds on cc.WorkStepEntityId equals mm
                                                   select cc;


                                    var process = _processesEntityRepository.Get(workStep.ProcessesEntityId);
                                    //获取
                                    var loadData = from loadPieceList in loadQuery.Where(d => d.WorkStepEntityId == workStep.Id).OrderBy(d => d.Sort)
                                                   join materialsList in queryMaterialsContent on loadPieceList.MaterialsContentId equals materialsList.Id
                                                   select loadPieceList;


                                    //获取该工步下所有的装入件
                                    var loadDataNo =( from loadPieceList in loadQuery.Where(d => d.WorkStepEntityId == workStep.Id).OrderBy(d => d.Sort)
                                                     select loadPieceList).ToList();
                                    if (loadData.Count() > 0)
                                    {
                                        var moduleLotNo = _bopDescRepository.FirstOrDefaultAsync(t => t.Id == workStepInput.BopDescId).Result;
                                        var collectContent = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.XJName == xjNameFive && t.XJDrawingNo == xjcodeFive && t.ModuleId == moduleLotNo.ModelId && t.SendTimeId == moduleLotNo.LotNoId).Result;
                                        if (collectContent != null)
                                        {
                                            // throw new UserFriendlyException("该节点下没有对应的芯级");

                                            var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectContent.XJId);
                                            if (collectBomMaterialsContentDtos == null)
                                            {
                                                result.Message = "该芯级下没有汇总数据，请检查";
                                                result.code = 1;
                                                return result;
                                            }
                                            //var storeStockContentFirst = _storeStockContentRepsitory.GetAll().Where(t => t.BomAnalysecontentId == collectContent.Id && t.ProductCodeId.Contains(collectContent.ModuleId.ToString()) && t.SendTimeId.Contains(collectContent.SendTimeId.ToString()));
                                            var storeStockContentFirst = stockContent.Where(t => t.BomAnalysecontentId == collectContent.Id && (t.ProductCodeId.Contains(collectContent.ModuleId.ToString()) && t.SendTimeId.Contains(collectContent.SendTimeId.ToString())) || t.ProductCode.Contains(moduleLotNo.Model + "系列"));
                                            var storeStockId = storeStockContentFirst.Select(t => t.StoreStockId).Distinct();

                                            //查询芯级下的所有配套数据
                                            var queryCollectMatingNumberAlys = from queryloadContent in collectBomMaterialsContentDtos.AsQueryable()
                                                                               join queryStoreStocks in queryStoreStockList on
                                                                             queryloadContent.MerialsId equals queryStoreStocks.MaterialsContentId
                                                                               join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                               select queryStoreStockContents;
                                            //查询芯级下的所有配套数据
                                            var queryCollectMatingNumber = from queryloadContent in loadData
                                                                           join queryStoreStocks in queryStoreStockList on
                                                                             queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                           join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                           where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                           select queryStoreStockContents;
                                            //汇总可预配套数量 汇总配套数据
                                            var queryyptListCount = from queryloadContent in loadList
                                                                    join queryStoreStocks in queryStoreStockList on
                                                                      queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                    join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                    where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                    select new StoreStockContent
                                                                    {
                                                                        ProductDrawingNo = queryStoreStockContents.ProductDrawingNo,
                                                                        Module = queryStoreStockContents.Module,
                                                                        WorkStepId = queryloadContent.WorkStepEntityId,
                                                                        StoreStockId = queryStoreStocks.Id,
                                                                        MaterialsContentId = queryStoreStocks.MaterialsContentId,
                                                                        BomAnalysecontentId = queryStoreStockContents.BomAnalysecontentId
                                                                    };
                                            var tempQuery = (from tempLoad in loadData
                                                            join tempStroeStocks in queryStoreStockList
                                                            on tempLoad.MaterialsContentId equals tempStroeStocks.MaterialsContentId
                                                            join storestocks in storeStockId on tempStroeStocks.Id equals storestocks
                                                            //join tempStockContent in _storeStockContentRepsitory.GetAll() on tempStroeStocks.Id equals tempStockContent.StoreStockId
                                                            join tempMaterial in queryMaterialsContent on tempStroeStocks.MaterialsContentId equals tempMaterial.Id
                                                                into tm
                                                            from tmi in tm.DefaultIfEmpty()
                                                            join tempNode in _materialsNodeRepository.GetAll() on tmi.MaterialsNodeId equals tempNode.Id
                                                            into tn
                                                            from tpn in tn.DefaultIfEmpty()
                                                                //join tempSearch in queryyptList on tempLoad ==null? Guid.Empty: tempLoad.MaterialsContentId equals (tempSearch == null ? Guid.Empty : tempSearch.MaterialsContentId) into ca
                                                                //from ts in ca.DefaultIfEmpty()
                                                            join tempSysCode in querySysCode on tmi.UnitId equals tempSysCode.Id
                                                               into sc
                                                            from cc in sc.DefaultIfEmpty()
                                                                //where (ts==null?Guid.Empty:ts.LoadDetailsId) == tempLoad.Id
                                                            orderby tempLoad.Sort
                                                            select new MatingTreeGridDto
                                                            {
                                                                data = new MatingEditParentData()
                                                                {
                                                                    HJFC = collectContent.SendTimeId.ToString(),
                                                                    HJXH = collectContent.ModuleId.ToString(),
                                                                    StoreStockId = tempStroeStocks.Id,
                                                                    Id = Guid.NewGuid(),
                                                                    CollectId = collectContent.Id,
                                                                    LoadDetailsId = tempLoad.Id,
                                                                    MaterialsTypeName = tpn == null ? "" : tpn.MaterialTypeName,//物料类别s
                                                                    Name = tempLoad.Name,// 物料名称
                                                                    Code = tmi == null ? "" : tempLoad.Code,//物料代码
                                                                    Module = tmi == null ? "" : tmi.Model,//规格
                                                                    Unit = cc == null ? "" : cc.Description,//单位
                                                                    Number = tempLoad.Number,//工艺用量
                                                                    MaterialsNodeName = tpn == null ? "" : tpn.MaterialTypeName,
                                                                    PreSuiteStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id),
                                                                    UsableMatingQuantityStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id),
                                                                    //queryyptListCount.FirstOrDefault(t => t.StoreStockId == storestocks).Quantity)
                                                                    WorkStepId = tempLoad.WorkStepEntityId,
                                                                    SuiteStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                    // 
                                                                    //tempStroeStocks.PreSuiteStock - tempStroeStocks.SuiteStock != 0 说明存在可用的配套数量 有可能存在负数
                                                                    //- ts.Quantity
                                                                    //&& tempLoad.Number - (tempStroeStocks.PreSuiteStock - tempStroeStocks.SuiteStock)>0
                                                                    StarvingStock = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= 0 ? 0 :
                                                             tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                    //queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id) > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? 0 :
                                                                    //     tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                    DeliveryStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.OutboundState == OutboundStates.出库),
                                                                    MatingStatusName = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) > 0 ? AssortStatus.缺料.ToString() :
                                                                         tempLoad.Number - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) && queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) != 0 && tempLoad.Number > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.配套中.ToString() : tempLoad.Number == queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.已配套.ToString() : "未配套",
                                                                    CompletePeople = queryCollectMatingNumber.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null) != null ? queryCollectMatingNumber.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null).CompletePeople : "",
                                                                    CompleteTime = queryCollectMatingNumber.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null) != null ? queryCollectMatingNumber.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null).CompleteTime.ToString() : "",
                                                                    PreSuiteName = queryCollectMatingNumberAlys.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) != null ? queryCollectMatingNumberAlys.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id).PreSuiteName : "",
                                                                    PreSuiteTime = queryCollectMatingNumberAlys.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) != null ? queryCollectMatingNumberAlys.FirstOrDefault(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id).PreSuiteTime.ToString() : "",
                                                                    ProductNumber = tempStroeStocks.ProductNumber,
                                                                    NodeLevel = 10
                                                                }
                                                            }).ToList();
                                            try
                                            {
                                                if (tempQuery.Count() > 0)
                                                {
                                                    var tempStore = (from tqy in loadDataNo
                                                                     join queryLoadData in tempQuery
                                                                     on tqy.Id equals queryLoadData.data.LoadDetailsId
                                                                     into qld
                                                                     from qlda in qld.DefaultIfEmpty()
                                                                     select new MatingTreeGridDto
                                                                     {
                                                                         data = new MatingEditParentData
                                                                         {
                                                                             HJXH = qlda == null ? "" : qlda.data.HJXH,
                                                                             HJFC = qlda == null ? "" : qlda.data.HJFC,
                                                                             CollectId = qlda == null ? Guid.Empty : qlda.data.CollectId,
                                                                             Code = qlda == null ? _storeFunctionsAppService.GetStandardDrawingNoDispose(tqy.Code).ProductDrawingNo : _storeFunctionsAppService.GetStandardDrawingNoDispose(qlda.data.Code).ProductDrawingNo,
                                                                             CompletePeople = qlda == null ? "" : qlda.data.CompletePeople,
                                                                             CompleteTime = qlda == null ? "" : qlda.data.CompleteTime,
                                                                             DeliveryStock = qlda == null ? 0 : qlda.data.DeliveryStock,
                                                                             Id = qlda == null ? Guid.Empty : qlda.data.Id,
                                                                             IsSuit = qlda == null ? 0 : qlda.data.IsSuit,
                                                                             JoinText = qlda == null ? "" : qlda.data.JoinText,
                                                                             LevelName = qlda == null ? "" : qlda.data.LevelName,
                                                                             LevelNum = qlda == null ? 0 : qlda.data.LevelNum,
                                                                             LoadDetailsId = qlda == null ? tqy.Id : qlda.data.LoadDetailsId,
                                                                             MaterialsNodeName = qlda == null ? "" : qlda.data.MaterialsNodeName,
                                                                             MaterialsTypeName = qlda == null ? "" : qlda.data.MaterialsTypeName,
                                                                             MatingStatus = qlda == null ? (int)AssortStatus.缺料 : qlda.data.MatingStatus,
                                                                             MatingStatusName = qlda == null ? "缺料" : qlda.data.MatingStatusName,
                                                                             Module = qlda == null ? _storeFunctionsAppService.GetStandardDrawingNoDispose(tqy.Code).Module : _storeFunctionsAppService.GetStandardDrawingNoDispose(qlda.data.Code).Module,
                                                                             Name = tqy.Name,
                                                                             NodeLevel = qlda == null ? 10 : qlda.data.NodeLevel,
                                                                             Number = qlda == null ? tqy.Number : qlda.data.Number,
                                                                             PreSuiteName = qlda == null ? "" : qlda.data.PreSuiteName,
                                                                             PreSuiteStock = qlda == null ? 0 : qlda.data.PreSuiteStock,
                                                                             PreSuiteTime = qlda == null ? "" : qlda.data.PreSuiteTime,
                                                                             ProductNumber = qlda == null ? "" : qlda.data.ProductNumber,
                                                                             StarvingStock = qlda == null ? 0 : qlda.data.StarvingStock,
                                                                             StoreStockId = qlda == null ? Guid.Empty : qlda.data.StoreStockId,
                                                                             SuiteStock = qlda == null ? 0 : qlda.data.SuiteStock,
                                                                             Unit = qlda == null ? "" : qlda.data.Unit,
                                                                             UsableMatingQuantityStock = qlda == null ? 0 : qlda.data.UsableMatingQuantityStock,
                                                                             UsableQuantityStock = qlda == null ? 0 : qlda.data.UsableQuantityStock,
                                                                             WorkStepId = qlda == null ? tqy.WorkStepEntityId : qlda.data.WorkStepId,
                                                                             XJName = qlda == null ? "" : qlda.data.XJName,
                                                                             YearsNo = qlda == null ? _storeFunctionsAppService.GetStandardDrawingNoDispose(tqy.Code).YearNo : _storeFunctionsAppService.GetStandardDrawingNoDispose(qlda.data.Code).YearNo
                                                                         }
                                                                     }
                                             ).ToList();
                                                    outputs = tempStore;
                                                }
                                                else
                                                {
                                                    var tempStore = (from tqy in loadDataNo
                                                                     join materContent in queryMaterialsContent on tqy.MaterialsContentId equals materContent.Id
                                                 into mc
                                                                     from msd in mc.DefaultIfEmpty()
                                                                     join materNode in _materialsNodeRepository.GetAll() on msd.MaterialsNodeId equals materNode.Id into mn
                                                                     from mnd in mn.DefaultIfEmpty()
                                                                     join sysCode in querySysCode on msd.UnitId equals sysCode.Id
                                                                     into syc
                                                                     from sy in syc.DefaultIfEmpty()
                                                                     select new MatingTreeGridDto
                                                                     {
                                                                         data = new MatingEditParentData
                                                                         {
                                                                             Code = _storeFunctionsAppService.GetStandardDrawingNoDispose(tqy.Code).ProductDrawingNo,
                                                                             LoadDetailsId = tqy.Id,
                                                                             Name = tqy.Name,
                                                                             Number = tqy.Number,
                                                                             MaterialsNodeName = mnd.MaterialTypeName,
                                                                             Module = _storeFunctionsAppService.GetStandardDrawingNoDispose(tqy.Code).Module,
                                                                             Unit = sy.Description,
                                                                             WorkStepId = tqy.WorkStepEntityId,
                                                                             YearsNo = _storeFunctionsAppService.GetStandardDrawingNoDispose(tqy.Code).YearNo,
                                                                             NodeLevel = 10
                                                                         }
                                                                     }
                                                   ).ToList();
                                                    outputs = tempStore;
                                                }
                                            }
                                            catch (Exception ex)
                                            {

                                                throw;
                                            }

                                        }
                                    }
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
                result.MatingTreeGridList = outputs;
                var tempData = _productionDesignAppService.DisplayRoute(input.NodeId);
                if (tempData != null)
                {
                    result.ProcessLineList = tempData.ProcessLineList;
                    result.ProcessNodeList = tempData.ProcessNodeList;
                }
                return result;
            }
            else
            {
                throw new Exception("传入数据有误!");
            }
        }
        /// <summary>
        /// 缺料统计
        /// </summary>
        /// <param name="id"></param>
        /// <param name="bopDescId"></param>
        /// <returns></returns>
        public async Task<List<MatingEditChildData>> GetStarvingContent(Guid id, Guid bopDescId)
        {
            var tempSech = await _productionSchedulerRepository.FirstOrDefaultAsync(id);
            if (tempSech != null)
            {
                Guid nodeId = tempSech.NodeId;
                MatingTreeResult result = new MatingTreeResult();

                if (nodeId != Guid.Empty)
                {
                    int route = GetRouteType(nodeId);
                    List<MatingTreeGridDto> outputs = new List<MatingTreeGridDto>();
                    var loadQuery = _loadPieceRepository.GetAll().ToList();
                    var stockContent = _storeStockContentRepsitory.GetAll().ToList();
                    var queryMaterialsContent = _materialsContentRepository.GetAll().ToList();
                    int Level = 0;
                    switch (route)
                    {
                        case 1:
                        case 2:
                            break;
                        case 3:
                            break;
                        case 4:
                            var proceTemp = _processesEntityRepository.Get(nodeId);
                            int numberCount = 0;
                            string xjcode = "";
                            string xjName = "";
                            //获取工序下的所有工步
                            var workTemp = _workStepEntityRepository.GetAll().Where(d => d.ProcessesEntityId == nodeId).OrderBy(d => d.WorkStepNumber).ToList();
                            if (workTemp.Count > 0)
                            {
                                var coreNodeInputList = (from temp in _bopNodeRepository.GetAll().Where(d => d.TechniqueEntityId == proceTemp.TechniqueEntityId)
                                                         select new
                                                         {
                                                             ParentCode = temp.ParentCode.Substring(0, 3),
                                                             BopDescId = temp.BopDescId
                                                         }).FirstOrDefault();
                                if (coreNodeInputList != null)
                                {
                                    var coreNode = _bopNodeRepository.GetAll().Where(d => d.NodeCode == coreNodeInputList.ParentCode && d.ParentId == coreNodeInputList.BopDescId).FirstOrDefault();
                                    if (coreNode != null)
                                    {
                                        xjcode = coreNode.NodeDrawingNo;
                                        xjName = coreNode.NodeName;
                                    }
                                    var moduleLotNo = _bopDescRepository.FirstOrDefaultAsync(t => t.Id == coreNode.BopDescId).Result;
                                    //找出所有的规程  （找到所有规程 能找到所有的装入件、contains）
                                    var techQuery = _bopNodeRepository.GetAll().Where(d => d.NodeCode.StartsWith(coreNode.NodeCode) && d.BopDescId == coreNode.BopDescId).Where(d => d.TechniqueEntityId != null).Select(d => d.TechniqueEntityId).ToList();
                                    var workIds = _workStepEntityRepository.GetAll().Where(d => techQuery.Contains(d.TechniqueEntityId)).Select(d => d.Id);
                                    //找出所有的装入件
                                    var loadList = (from cc in loadQuery
                                                    join mm in workIds on cc.WorkStepEntityId equals mm
                                                    select cc).ToList();
                                    //找出所有工步的id
                                    var workIdList = workTemp.Select(d => d.Id).ToList();
                                    //根据工步获取装入件明细 所有工步下的装入件明细

                                    //var lo = _loadPieceRepository.GetAll().Where(d => workIdList.Contains(d.WorkStepEntityId)).OrderBy(d => d.Sort);

                                    var loadData = (from loadPieceList in _loadPieceRepository.GetAll().Where(d => workIdList.Contains(d.WorkStepEntityId)).OrderBy(d => d.Sort)
                                                    join materialsList in queryMaterialsContent on loadPieceList.MaterialsContentId equals materialsList.Id
                                                    into mll
                                                    from ml in mll.DefaultIfEmpty()
                                                    select loadPieceList).AsNoTracking().ToList();
                                    //找出预配套的数量
                                    List<MatingEditChildData> tempQuerylist = new List<MatingEditChildData>();

                                    if (loadData.Count() > 0)
                                    {
                                       
                                        var collectContent = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.XJName == xjName && t.XJDrawingNo == xjcode && t.ModuleId == moduleLotNo.ModelId && t.SendTimeId == moduleLotNo.LotNoId).Result;
                                        if (collectContent == null)
                                        {
                                            throw new UserFriendlyException("该节点下没有对应的芯级");
                                        }
                                        var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectContent.XJId);
                                        if (collectBomMaterialsContentDtos == null || collectContent == null)
                                        {
                                            result.Message = "该芯级下没有汇总数据，请检查";
                                            result.code = 1;
                                            return null;
                                        }
                                        var storeStockContentFirst = stockContent.Where(t => t.BomAnalysecontentId == collectContent.Id && t.ProductCodeId.Contains(collectContent.ModuleId.ToString()) && t.SendTimeId.Contains(collectContent.SendTimeId.ToString()));
                                        var storeStockId = storeStockContentFirst.Select(t => t.StoreStockId).Distinct().ToList();
                                        //查询芯级下的所有预配套数据
                                        var queryCollectMatingNumberAlys = from queryloadContent in collectBomMaterialsContentDtos.AsQueryable()
                                                                           join queryStoreStocks in _storeStockRepsitory.GetAll() on
                                                                         queryloadContent.MerialsId equals queryStoreStocks.MaterialsContentId
                                                                           join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                           select queryStoreStockContents;
                                        //查询芯级下的所有配套数据
                                        var queryCollectMatingNumber = (from queryloadContent in loadData
                                                                       join queryStoreStocks in _storeStockRepsitory.GetAll() on
                                                                         queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                       join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                       where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                       select queryStoreStockContents).ToList();

                                        //汇总可预配套数量 汇总配套数据
                                        var queryyptListCount = (from queryloadContent in loadList
                                                                join queryStoreStocks in _storeStockRepsitory.GetAll() on
                                                                  queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                select new StoreStockContent
                                                                {
                                                                    ProductDrawingNo = queryStoreStockContents.ProductDrawingNo,
                                                                    Module = queryStoreStockContents.Module,
                                                                    WorkStepId = queryloadContent.WorkStepEntityId,
                                                                    StoreStockId = queryStoreStocks.Id,
                                                                    MaterialsContentId = queryStoreStocks.MaterialsContentId,
                                                                    BomAnalysecontentId = queryStoreStockContents.BomAnalysecontentId
                                                                }).ToList();
                                        try
                                        {
                                            var tempQuery = (from tempLoad in loadData
                                                             join tempStroeStocks in _storeStockRepsitory.GetAll()
                                                             on tempLoad.MaterialsContentId equals tempStroeStocks.MaterialsContentId
                                                             join storestocks in storeStockId on tempStroeStocks.Id equals storestocks
                                                             //join tempStockContent in _storeStockContentRepsitory.GetAll() on tempStroeStocks.Id equals tempStockContent.StoreStockId
                                                             join tempMaterial in queryMaterialsContent on tempStroeStocks.MaterialsContentId equals tempMaterial.Id
                                                                 into tm
                                                             from tmi in tm.DefaultIfEmpty()
                                                                 //join queryyptlistCount in queryyptListCount on storestocks == null?Guid.Empty: storestocks equals queryyptlistCount ==null?Guid.Empty: queryyptlistCount.StoreStockId
                                                                 //into qlc from ql in qlc.DefaultIfEmpty()
                                                             join tempNode in _materialsNodeRepository.GetAll() on tmi.MaterialsNodeId equals tempNode.Id
                                                             into tn
                                                             from tpn in tn.DefaultIfEmpty()
                                                                 //join tempSearch in queryyptList on tempLoad ==null? Guid.Empty: tempLoad.MaterialsContentId equals (tempSearch == null ? Guid.Empty : tempSearch.MaterialsContentId) into ca
                                                                 //from ts in ca.DefaultIfEmpty()
                                                             join tempSysCode in _sysCodeRepository.GetAll() on tmi.UnitId equals tempSysCode.Id
                                                                into sc
                                                             from cc in sc.DefaultIfEmpty()
                                                                 //where (ts == null ? Guid.Empty : ts.LoadDetailsId) == tempLoad.Id
                                                             orderby tempLoad.Sort
                                                             select new MatingEditChildData
                                                             {
                                                                 Code = tmi == null ? "" : tmi.MaterialNo,//物料代码
                                                                 Module = tmi == null ? "" : tmi.Model,//规格
                                                                 StoreStockId = tempStroeStocks.Id,
                                                                 CollectId = collectContent.Id,
                                                                 Number = tempLoad.Number,//工艺用量
                                                                 Unit = cc == null ? "" : cc.Description,//单位
                                                                 MaterialsNodeName = tpn == null ? "" : tpn.MaterialTypeName,
                                                                 Id = tempLoad.MaterialsContentId,
                                                                 LoadDetailsId = tempLoad.Id,
                                                                 SuiteStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                 PreSuiteStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id),
                                                                 UsableMatingQuantityStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id),
                                                                 StarvingStock = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= 0 ? 0 :
                                                                 tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                 MatingStatusName = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) > 0 ? AssortStatus.缺料.ToString() :
                                                                 tempLoad.Number - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) && queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) != 0 && tempLoad.Number > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.配套中.ToString() : tempLoad.Number == queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.已配套.ToString() : "未配套"
                                                             }).ToList();
                                            var tempStore = (from tqy in loadData
                                                             join materContent in queryMaterialsContent on tqy.MaterialsContentId equals materContent.Id
                                                             into mc
                                                             from msd in mc.DefaultIfEmpty()
                                                             join materNode in _materialsNodeRepository.GetAll() on msd.MaterialsNodeId equals materNode.Id into mn
                                                             from mnd in mn.DefaultIfEmpty()
                                                             join queryLoadData in tempQuery on tqy.Id equals queryLoadData.LoadDetailsId
                                                             into qld
                                                             from qlda in qld.DefaultIfEmpty()
                                                             join sysCode in _sysCodeRepository.GetAll() on msd.UnitId equals sysCode.Id
                                                             into syc
                                                             from sy in syc.DefaultIfEmpty()
                                                             select new MatingEditChildData
                                                             {
                                                                 CollectId = qlda == null ? collectContent.Id : qlda.CollectId,
                                                                 Code = qlda == null ? tqy.Code : qlda.Code,
                                                                 DeliveryStock = qlda == null ? 0 : qlda.DeliveryStock,
                                                                 LoadDetailsId = qlda == null ? tqy.Id : qlda.LoadDetailsId,
                                                                 MaterialsNodeName = qlda == null ? mnd.MaterialTypeName : qlda.MaterialsNodeName,
                                                                 MatingStatusName = qlda == null ? "缺料" : qlda.MatingStatusName,
                                                                 Module = qlda == null ? msd.Model : qlda.Module,
                                                                 Name = qlda == null ? msd.MaterialName : msd.MaterialName,
                                                                 Number = qlda == null ? tqy.Number : qlda.Number,
                                                                 PreSuiteStock = qlda == null ? 0 : qlda.PreSuiteStock,
                                                                 StarvingStock = qlda == null ? tqy.Number : qlda.StarvingStock,
                                                                 Id = qlda == null ? Guid.Empty : tqy.MaterialsContentId,
                                                                 //StoreStockId = qlda == null ? Guid.Empty : qlda.StoreStockId,
                                                                 SuiteStock = qlda == null ? 0 : qlda.SuiteStock,
                                                                 Unit = qlda == null ? sy.Description : qlda.Unit,
                                                                 UsableMatingQuantityStock = qlda == null ? 0 : qlda.UsableMatingQuantityStock,
                                                             }
                                                           ).ToList();
                                            //计算工艺用量
                                            var contentMatingRequest = from tm in (from tmp in tempStore select tmp)
                                                                       group tm by new { tm.Code, tm.Module, tm.PreSuiteStock, tm.UsableMatingQuantityStock, tm.CollectId, tm.Unit, tm.Name, tm.MaterialsNodeName } into grouptm
                                                                       select new
                                                                       {
                                                                           Module = grouptm.Key.Module,
                                                                           Code = grouptm.Key.Code,
                                                                           PreSuiteStock = grouptm.Key.PreSuiteStock,
                                                                           UsableMatingQuantityStock = grouptm.Key.UsableMatingQuantityStock,
                                                                           Number = grouptm.Sum(t => t.Number),
                                                                           Name = grouptm.Key.Name,
                                                                           MaterialsNodeName = grouptm.Key.MaterialsNodeName,
                                                                           Unit = grouptm.Key.Unit
                                                                       };
                                            var starvingContent = tempStore.Where(t => t.MatingStatusName == "缺料");
                                            if (starvingContent.Count() == 0)
                                            {
                                                return tempQuerylist;
                                            }

                                            //计算提取芯级预配套数量、可用预配套数量 进行去重
                                            var contentRequest = starvingContent.ToList().Select(x => new { x.Code, x.Module, x.PreSuiteStock, x.UsableMatingQuantityStock, x.CollectId, x.Unit, x.Name, x.MaterialsNodeName }).Distinct();
                                            //进行关联
                                            var unionAll = from temp in contentRequest
                                                           join cmt in contentMatingRequest on
                               new { no = temp.Module, mod = temp.Code } equals new { no = cmt.Module, mod = cmt.Code }
                                                           select new
                                                           {
                                                               Module = temp.Module,
                                                               Code = temp.Code,
                                                               Number = cmt.Number,
                                                               PreSuiteStock = temp.PreSuiteStock,
                                                               UsableMatingQuantityStock = temp.UsableMatingQuantityStock,
                                                               Unit = cmt.Unit,
                                                               Name = cmt.Name,
                                                               MaterialsNodeName = cmt.MaterialsNodeName
                                                           };
                                            //计算配套数量缺料数量的汇总
                                            var groupByBtContent = from groupContent in (from queryStoreStock in starvingContent select queryStoreStock)
                                                                   group groupContent by new { groupContent.CollectId, groupContent.Module, groupContent.Code, groupContent.Unit, groupContent.MaterialsNodeName, groupContent.Name } into gc
                                                                   select new MatingEditChildData
                                                                   {
                                                                       PreSuiteStock = unionAll.Where(t => t.Module == gc.Key.Module && t.Code == gc.Key.Code).Sum(t => t.PreSuiteStock),
                                                                       UsableMatingQuantityStock = unionAll.Where(t => t.Module == gc.Key.Module && t.Code == gc.Key.Code).Sum(t => t.UsableMatingQuantityStock),//可用预配套数量
                                                                       SuiteStock = gc.Sum(t => t.SuiteStock),
                                                                       StarvingStock = gc.Sum(t => t.StarvingStock),
                                                                       DeliveryStock = gc.Sum(t => t.DeliveryStock),
                                                                       CollectId = gc.Key.CollectId,
                                                                       Number = unionAll.Where(t => t.Module == gc.Key.Module && t.Code == gc.Key.Code).Sum(t => t.Number),
                                                                       Module = gc.Key.Module,
                                                                       Code = gc.Key.Code,
                                                                       Unit = gc.Key.Unit,
                                                                       Name = gc.Key.Name,
                                                                       MaterialsNodeName = gc.Key.MaterialsNodeName

                                                                   };
                                            if (groupByBtContent != null && groupByBtContent.Count() > 0)
                                            {
                                                tempQuerylist.AddRange(groupByBtContent.ToList());
                                            }
                                            return tempQuerylist;
                                        }
                                        catch (Exception ex)
                                        {

                                            throw;
                                        }

                                    }
                                }

                            }
                            break;
                        case 5:
                            var workStep = _workStepEntityRepository.FirstOrDefault(d => d.Id == nodeId);
                            string xjcodeFive = "";
                            string xjNameFive = "";
                            if (workStep != null)
                            {

                                var workStepInput = (from temp in _bopNodeRepository.GetAll().Where(d => d.TechniqueEntityId == workStep.TechniqueEntityId)
                                                     select new
                                                     {
                                                         ParentCode = temp.ParentCode.Substring(0, 3),
                                                         BopDescId = temp.BopDescId
                                                     }).FirstOrDefault();
                                if (workStepInput != null)
                                {
                                    var moduleLotNo = _bopDescRepository.FirstOrDefaultAsync(t => t.Id == workStepInput.BopDescId).Result;
                                    var coreNode = _bopNodeRepository.GetAll().Where(d => d.NodeCode == workStepInput.ParentCode && d.BopDescId == workStepInput.BopDescId).FirstOrDefault();
                                    if (coreNode != null)
                                    {
                                        xjNameFive = coreNode.NodeName;
                                        xjcodeFive = coreNode.NodeDrawingNo;
                                    }
                                    List<MatingEditChildData> tempQuerylist = new List<MatingEditChildData>();
                                    var techQuery = _bopNodeRepository.GetAll().Where(d => d.NodeCode.StartsWith(coreNode.NodeCode) && d.BopDescId == coreNode.BopDescId).Where(d => d.TechniqueEntityId != null).Select(d => d.TechniqueEntityId).ToList();
                                    if (techQuery.Count > 0)
                                    {

                                        var workIds = _workStepEntityRepository.GetAll().Where(d => techQuery.Contains(d.TechniqueEntityId)).Select(d => d.Id);

                                        //获取或有的装入件
                                        var loadList = (from cc in loadQuery
                                                        join mm in workIds on cc.WorkStepEntityId equals mm
                                                        select cc).ToList();


                                        var process = _processesEntityRepository.Get(workStep.ProcessesEntityId);
                                        //获取
                                        var loadData = (from loadPieceList in _loadPieceRepository.GetAll().Where(d => d.WorkStepEntityId == workStep.Id).OrderBy(d => d.Sort)
                                                       join materialsList in queryMaterialsContent on loadPieceList.MaterialsContentId equals materialsList.Id
                                                       select loadPieceList).ToList();


                                        //获取该工步下所有的装入件
                                        var loadDataNo = (from loadPieceList in _loadPieceRepository.GetAll().Where(d => d.WorkStepEntityId == workStep.Id).OrderBy(d => d.Sort)
                                                         select loadPieceList).ToList();
                                        if (loadData.Count() > 0)
                                        {
                                            var collectContent = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.XJName == xjNameFive && t.XJDrawingNo == xjcodeFive && t.ModuleId == moduleLotNo.ModelId && t.SendTimeId == moduleLotNo.LotNoId).Result;
                                            if (collectContent == null)
                                            {
                                                throw new UserFriendlyException("该节点下没有对应的芯级");
                                            }
                                            var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectContent.XJId);
                                            if (collectBomMaterialsContentDtos == null || collectContent == null)
                                            {
                                                result.Message = "该芯级下没有汇总数据，请检查";
                                                result.code = 1;
                                                return null;
                                            }
                                            var storeStockContentFirst = stockContent.Where(t => t.BomAnalysecontentId == collectContent.Id && t.ProductCodeId.Contains(collectContent.ModuleId.ToString()) && t.SendTimeId.Contains(collectContent.SendTimeId.ToString()));
                                            var storeStockId = storeStockContentFirst.Select(t => t.StoreStockId).Distinct();

                                            //查询芯级下的所有配套数据
                                            var queryCollectMatingNumberAlys = from queryloadContent in collectBomMaterialsContentDtos.AsQueryable()
                                                                               join queryStoreStocks in _storeStockRepsitory.GetAll() on
                                                                             queryloadContent.MerialsId equals queryStoreStocks.MaterialsContentId
                                                                               join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                               select queryStoreStockContents;
                                            var adfaff = queryCollectMatingNumberAlys.ToList();
                                            //查询芯级下的所有配套数据
                                            var queryCollectMatingNumber = from queryloadContent in loadData
                                                                           join queryStoreStocks in _storeStockRepsitory.GetAll() on
                                                                             queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                           join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                           where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                           select queryStoreStockContents;
                                            //var adfaffa = queryCollectMatingNumber.ToList();
                                            //汇总可预配套数量 汇总配套数据
                                            var queryyptListCount = from queryloadContent in loadList
                                                                    join queryStoreStocks in _storeStockRepsitory.GetAll() on
                                                                      queryloadContent.MaterialsContentId equals queryStoreStocks.MaterialsContentId
                                                                    join queryStoreStockContents in stockContent.Where(t => t.Batch == "01" && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null && t.BomAnalysecontentId == collectContent.Id) on queryStoreStocks.Id equals queryStoreStockContents.StoreStockId
                                                                    where queryStoreStockContents.LoadDetailsId == queryloadContent.Id
                                                                    select new StoreStockContent
                                                                    {
                                                                        ProductDrawingNo = queryStoreStockContents.ProductDrawingNo,
                                                                        Module = queryStoreStockContents.Module,
                                                                        WorkStepId = queryloadContent.WorkStepEntityId,
                                                                        StoreStockId = queryStoreStocks.Id,
                                                                        MaterialsContentId = queryStoreStocks.MaterialsContentId,
                                                                        BomAnalysecontentId = queryStoreStockContents.BomAnalysecontentId
                                                                    };
                                          //  var adfafff = queryyptListCount.ToList();
                                            var tempQuery = from tempLoad in loadData
                                                            join tempStroeStocks in _storeStockRepsitory.GetAll()
                                                            on tempLoad.MaterialsContentId equals tempStroeStocks.MaterialsContentId
                                                            join storestocks in storeStockId on tempStroeStocks.Id equals storestocks
                                                            //join tempStockContent in _storeStockContentRepsitory.GetAll() on tempStroeStocks.Id equals tempStockContent.StoreStockId
                                                            join tempMaterial in queryMaterialsContent on tempStroeStocks.MaterialsContentId equals tempMaterial.Id
                                                                into tm
                                                            from tmi in tm.DefaultIfEmpty()
                                                            join tempNode in _materialsNodeRepository.GetAll() on tmi.MaterialsNodeId equals tempNode.Id
                                                            into tn
                                                            from tpn in tn.DefaultIfEmpty()
                                                                //join tempSearch in queryyptList on tempLoad ==null? Guid.Empty: tempLoad.MaterialsContentId equals (tempSearch == null ? Guid.Empty : tempSearch.MaterialsContentId) into ca
                                                                //from ts in ca.DefaultIfEmpty()
                                                            join tempSysCode in _sysCodeRepository.GetAll() on tmi.UnitId equals tempSysCode.Id
                                                               into sc
                                                            from cc in sc.DefaultIfEmpty()
                                                                //where (ts==null?Guid.Empty:ts.LoadDetailsId) == tempLoad.Id
                                                            orderby tempLoad.Sort
                                                            select new MatingEditChildData
                                                            {
                                                                HJFC = collectContent.SendTimeId.ToString(),
                                                                HJXH = collectContent.ModuleId.ToString(),
                                                                StoreStockId = tempStroeStocks.Id,
                                                                Id = Guid.NewGuid(),
                                                                CollectId = collectContent.Id,
                                                                LoadDetailsId = tempLoad.Id,
                                                                MaterialsTypeName = tpn == null ? "" : tpn.MaterialTypeName,//物料类别s
                                                                Name = tempLoad.Name,// 物料名称
                                                                Code = tmi == null ? "" : tmi.MaterialNo,//物料代码
                                                                Module = tmi == null ? "" : tmi.Model,//规格
                                                                Unit = cc == null ? "" : cc.Description,//单位
                                                                Number = tempLoad.Number,//工艺用量
                                                                MaterialsNodeName = tpn == null ? "" : tpn.MaterialTypeName,
                                                                PreSuiteStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id),
                                                                UsableMatingQuantityStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id),
                                                                //queryyptListCount.FirstOrDefault(t => t.StoreStockId == storestocks).Quantity)
                                                                WorkStepId = tempLoad.WorkStepEntityId,
                                                                SuiteStock = queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                // 
                                                                //tempStroeStocks.PreSuiteStock - tempStroeStocks.SuiteStock != 0 说明存在可用的配套数量 有可能存在负数
                                                                //- ts.Quantity
                                                                //&& tempLoad.Number - (tempStroeStocks.PreSuiteStock - tempStroeStocks.SuiteStock)>0
                                                                StarvingStock = queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id) > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? 0 :
                                                                         tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id),
                                                                DeliveryStock = tempStroeStocks.DeliveryStock,
                                                                MatingStatusName = tempLoad.Number - (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id) - queryyptListCount.Count(t => t.StoreStockId == tempStroeStocks.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) > 0 ? AssortStatus.缺料.ToString() :
                                                                         tempLoad.Number - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) <= (queryCollectMatingNumberAlys.Count(t => t.StoreStockId == tempStroeStocks.Id && t.BomAnalysecontentId == collectContent.Id)) - queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) && queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) != 0 && tempLoad.Number > queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.配套中.ToString() : tempLoad.Number == queryCollectMatingNumber.Count(t => t.StoreStockId == tempStroeStocks.Id && t.WorkStepId == tempLoad.WorkStepEntityId && t.LoadDetailsId == tempLoad.Id) ? AssortStatus.已配套.ToString() : "未配套",
                                                                CompletePeople = tempStroeStocks.CompletePeople,
                                                                CompleteTime = tempStroeStocks.CompleteTime.ToString(),
                                                                PreSuiteName = tempStroeStocks.PreSuiteName,
                                                                PreSuiteTime = tempStroeStocks.PreSuiteTime.ToString(),
                                                                ProductNumber = tempStroeStocks.ProductNumber,
                                                                NodeLevel = 10

                                                            };

                                            var asdfa = tempQuery.ToList();
                                            List<MatingEditChildData> matingEditChildDatas = new List<MatingEditChildData>();
                                            try
                                            {
                                                if (tempQuery.Count() > 0)
                                                {
                                                    matingEditChildDatas = (from tqy in loadData
                                                                            join materContent in queryMaterialsContent on tqy.MaterialsContentId equals materContent.Id
                                                                            into mc
                                                                            from msd in mc.DefaultIfEmpty()
                                                                            join materNode in _materialsNodeRepository.GetAll() on msd.MaterialsNodeId equals materNode.Id into mn
                                                                            from mnd in mn.DefaultIfEmpty()
                                                                            join queryLoadData in tempQuery on tqy.Id equals queryLoadData.LoadDetailsId == null ? Guid.Empty : queryLoadData.LoadDetailsId
                                                                            into qld
                                                                            from qlda in qld.DefaultIfEmpty()
                                                                            join sysCode in _sysCodeRepository.GetAll() on msd.UnitId equals sysCode.Id
                                                                            into syc
                                                                            from sy in syc.DefaultIfEmpty()
                                                                            select new MatingEditChildData
                                                                            {
                                                                                CollectId = qlda == null ? collectContent.Id : qlda.CollectId,
                                                                                Code = qlda == null ? tqy.Code : qlda.Code,
                                                                                DeliveryStock = qlda == null ? 0 : qlda.DeliveryStock,
                                                                                LoadDetailsId = qlda == null ? tqy.Id : qlda.LoadDetailsId,
                                                                                MaterialsNodeName = qlda == null ? mnd.MaterialTypeName : qlda.MaterialsNodeName,
                                                                                MatingStatusName = qlda == null ? "缺料" : qlda.MatingStatusName,
                                                                                Module = qlda == null ? "" : qlda.Module,
                                                                                Name = qlda == null ? "" : tqy.Name,
                                                                                Number = qlda == null ? tqy.Number : qlda.Number,
                                                                                PreSuiteStock = qlda == null ? 0 : qlda.PreSuiteStock,
                                                                                StarvingStock = qlda == null ? tqy.Number : qlda.StarvingStock,
                                                                                Id = qlda == null ? Guid.Empty : tqy.MaterialsContentId,
                                                                                SuiteStock = qlda == null ? 0 : qlda.SuiteStock,
                                                                                Unit = qlda == null ? sy.Description : qlda.Unit,
                                                                                UsableMatingQuantityStock = qlda == null ? 0 : qlda.UsableMatingQuantityStock
                                                                            }).ToList();
                                                }
                                                else
                                                {
                                                    matingEditChildDatas = (from tqy in loadData
                                                                            join materContent in queryMaterialsContent on tqy.MaterialsContentId equals materContent.Id
                                                                            into mc
                                                                            from msd in mc.DefaultIfEmpty()
                                                                            join materNode in _materialsNodeRepository.GetAll() on msd.MaterialsNodeId equals materNode.Id into mn
                                                                            from mnd in mn.DefaultIfEmpty()
                                                                            join sysCode in _sysCodeRepository.GetAll() on msd.UnitId equals sysCode.Id
                                                                            into syc
                                                                            from sy in syc.DefaultIfEmpty()
                                                                            select new MatingEditChildData
                                                                            {
                                                                                CollectId = collectContent.Id,
                                                                                Code = tqy.Code,
                                                                                DeliveryStock = 0,
                                                                                LoadDetailsId = tqy.Id,
                                                                                MaterialsNodeName = mnd.MaterialTypeName,
                                                                                MatingStatusName = "缺料",
                                                                                Module = msd.Model,
                                                                                Name = tqy.Name,
                                                                                Number = tqy.Number,
                                                                                PreSuiteStock = 0,
                                                                                StarvingStock = tqy.Number,
                                                                                Id = tqy.MaterialsContentId,
                                                                                SuiteStock = 0,
                                                                                Unit = sy.Description,
                                                                                UsableMatingQuantityStock = 0
                                                                            }).ToList();
                                                }
                                                var starvingContent = matingEditChildDatas.Where(t => t.MatingStatusName == "缺料");
                                                if (starvingContent != null && starvingContent.Count() > 0)
                                                {
                                                    tempQuerylist.AddRange(starvingContent.ToList());
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                throw;
                                            }
                                            return tempQuerylist;
                                        }
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }
                    return new List<MatingEditChildData>();
                }
                else
                {
                    throw new Exception("传入数据有误!");
                }

            }
            else
            {
                throw new Exception("未查找到匹配的计划!");
            }
        }
        /// <summary>
        /// 自动配套
        /// </summary>
        /// <param name="matingTreeGridDto"></param>
        /// <param name="pattern">配套模式</param>
        /// <returns></returns>
        public async Task<ResultMessage> MatingExecute(List<MatingTreeGridDto> matingTreeGridDto)
        {
            ResultMessage resultMessage = new ResultMessage();

            try
            {
                var userId = GetCurrentUser().Id; //add 11/30
                var userData = _userRepository.FirstOrDefaultAsync(t => t.Id == userId).Result;
                if (matingTreeGridDto.Count == 0)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "此节点不能进行配套！";
                    return resultMessage;
                    //throw new UserFriendlyException("此节点不能进行配套！");
                }
                matingTreeGridDto = matingTreeGridDto.Where(t => t.data.PreSuiteStock != 0 && t.data.Number != 0).ToList();
                MatingEditParentData editParentData = new MatingEditParentData();
                if (matingTreeGridDto != null)
                {
                    foreach (MatingTreeGridDto matingTreeGrid in matingTreeGridDto)
                    {
                        //有子级 针对于含有父级的
                        if (matingTreeGrid.children.Count > 0)
                        {
                            List<MatingDetaillist> matingDetaillist = matingTreeGrid.children;
                            if (matingDetaillist.Count() > 0)
                            {
                                matingDetaillist.ForEach(t =>
                                {
                                    switch (t.data.MatingStatus)
                                    {
                                        case (int)AssortStatus.未配套:
                                            #region 计算数量
                                            //根据id获取库存主表相关信息     

                                            var storeStocks = _storeStockRepsitory.Get(editParentData.StoreStockId);
                                            //计算数量 更新库存信息主表数据
                                            //芯级预配套数量：设计bom的芯级预配套配套数量
                                            //可用预配套数量：芯级预配套数量-配套数量
                                            storeStocks.UsableMatingQuantityStock = matingTreeGrid.data.UsableMatingQuantityStock - matingTreeGrid.data.SuiteStock;
                                            //配套数量== 可用预配套数量
                                            storeStocks.SuiteStock = matingTreeGrid.data.UsableMatingQuantityStock;
                                            //缺料数量 工艺用量 -配套数量  
                                            storeStocks.StarvingStock = matingTreeGrid.data.Number - storeStocks.SuiteStock;
                                            //出库数量 （查询时计算） 
                                            storeStocks.DeliveryStock = matingTreeGrid.data.DeliveryStock;
                                            //工艺用量 -配套数量  > 可用预配套数量
                                            if (storeStocks.StarvingStock > matingTreeGrid.data.UsableMatingQuantityStock)
                                            {
                                                storeStocks.MatingStatus = (int)AssortStatus.缺料;
                                            }
                                            //工艺用量  =  配套数量
                                            else if (matingTreeGrid.data.Number == storeStocks.SuiteStock)
                                            {
                                                storeStocks.MatingStatus = (int)AssortStatus.已配套;
                                            }
                                            //工艺用量 - 配套数量  ≤ 可用预配套数量
                                            else if (storeStocks.StarvingStock <= matingTreeGrid.data.UsableMatingQuantityStock)
                                            {
                                                storeStocks.MatingStatus = (int)AssortStatus.配套中;
                                            }
                                            else
                                            {
                                                storeStocks.MatingStatus = (int)AssortStatus.未配套;
                                            }
                                            //配套人 、配套时间、
                                            storeStocks.CompletePeople = userData.Surname + userData.Name;
                                            storeStocks.CompleteTime = DateTime.Now;
                                            //更新库存主表数据
                                            _storeStockRepsitory.UpdateAsync(storeStocks);
                                            #endregion
                                            #region 更新库存子表数据 
                                            //查出全部的已经预配套的零件 条件 已预配套、预配套id不等于null、配套id等于null 根据工艺用量取
                                            var queryStoreStockConetnList = _storeStockContentRepsitory.GetAll().Where(c => c.StoreStockId == storeStocks.Id && c.IsPreSuit == IsSuits.是 && c.BomAnalysecontentId != null && c.LoadDetailsId == null).OrderBy(c => c.CreationTime).Take(matingTreeGrid.data.Number);
                                            //更新子表数据
                                            //加保险
                                            if (queryStoreStockConetnList.Count() > 0)
                                            {
                                                foreach (StoreStockContent storeStockContent in queryStoreStockConetnList)
                                                {
                                                    storeStockContent.LoadDetailsId = matingTreeGrid.data.LoadDetailsId;
                                                    storeStockContent.IsSuit = IsSuits.是;
                                                    storeStockContent.CompletePeople = userData.Surname + userData.Name;
                                                    storeStockContent.CompleteTime = DateTime.Now;
                                                    _storeStockContentRepsitory.UpdateAsync(storeStockContent);
                                                }
                                            }
                                            #endregion


                                            break;
                                        case (int)AssortStatus.配套中:

                                            #region 计算数量
                                            //根据id获取库存主表相关信息
                                            storeStocks = _storeStockRepsitory.Get(editParentData.StoreStockId);
                                            //计算数量 更新库存信息主表数据
                                            //芯级预配套数量：设计bom的芯级预配套配套数量
                                            //（预配套数量 -配套数量 ：计算可用数量）
                                            int sl = storeStocks.PreSuiteStock - matingTreeGrid.data.SuiteStock;
                                            //可用预配套数量：预配套数量- 1
                                            storeStocks.UsableMatingQuantityStock -= sl;
                                            //配套数量 += 可用预配套数量
                                            storeStocks.SuiteStock += matingTreeGrid.data.UsableMatingQuantityStock;

                                            //缺料数量 
                                            storeStocks.StarvingStock = 0;
                                            //出库数量 （查询时计算）
                                            storeStocks.DeliveryStock = matingTreeGrid.data.DeliveryStock;

                                            storeStocks.MatingStatus = (int)AssortStatus.已配套;


                                            ////工艺用量 -配套数量  > 可用预配套数量
                                            //if (storeStocks.StarvingStock > matingTreeGrid.data.UsableMatingQuantityStock)
                                            //{
                                            //    storeStocks.MatingStatus = (int)AssortStatus.缺料;
                                            //}
                                            ////工艺用量  =  配套数量
                                            //else if (matingTreeGrid.data.Number == storeStocks.SuiteStock)
                                            //{
                                            //    storeStocks.MatingStatus = (int)AssortStatus.已配套;
                                            //}
                                            ////工艺用量 - 配套数量  ≤ 可用预配套数量
                                            //else if (storeStocks.StarvingStock <= matingTreeGrid.data.UsableMatingQuantityStock)
                                            //{
                                            //    storeStocks.MatingStatus = (int)AssortStatus.配套中;
                                            //}
                                            //else
                                            //{
                                            //    storeStocks.MatingStatus = (int)AssortStatus.未配套;
                                            //}
                                            //配套人 、配套时间、
                                            storeStocks.CompletePeople = userData.Surname + userData.Name;
                                            storeStocks.CompleteTime = DateTime.Now;
                                            //更新库存主表数据
                                            _storeStockRepsitory.UpdateAsync(storeStocks);
                                            #endregion
                                            #region 更新库存子表数据 
                                            //查出全部的已经预配套的零件 条件 已预配套、预配套id不等于null、配套id等于null 根据工艺用量取
                                            queryStoreStockConetnList = _storeStockContentRepsitory.GetAll().Where(c => c.StoreStockId == storeStocks.Id && c.IsPreSuit == IsSuits.是 && c.BomAnalysecontentId != null && c.LoadDetailsId == null).OrderBy(c => c.CreationTime).Take(matingTreeGrid.data.Number);
                                            //更新子表数据
                                            //加保险
                                            if (queryStoreStockConetnList.Count() > 0)
                                            {
                                                foreach (StoreStockContent storeStockContent in queryStoreStockConetnList)
                                                {
                                                    storeStockContent.LoadDetailsId = matingTreeGrid.data.LoadDetailsId;
                                                    storeStockContent.IsSuit = IsSuits.是;
                                                    storeStockContent.CompletePeople = userData.Surname + userData.Name;
                                                    storeStockContent.CompleteTime = DateTime.Now;
                                                    _storeStockContentRepsitory.UpdateAsync(storeStockContent);
                                                }
                                            }

                                            #endregion

                                            break;
                                        case (int)AssortStatus.缺料:

                                            #region 计算数量
                                            //根据id获取库存主表相关信息
                                            storeStocks = _storeStockRepsitory.Get(editParentData.StoreStockId);
                                            //计算数量 更新库存信息主表数据
                                            //芯级预配套数量：设计bom的芯级预配套配套数量
                                            // storeStocks.PreSuiteStock =

                                            //预配套数量
                                            int preSuiteStock = storeStocks.PreSuiteStock;
                                            storeStocks.UsableMatingQuantityStock = storeStocks.PreSuiteStock - matingTreeGrid.data.SuiteStock;
                                            //如果预配套数量>=缺料数量  并且 预配套数量
                                            //if (preSuiteStock >= editParentData.StarvingStock)
                                            //{
                                            //    storeStocks.UsableMatingQuantityStock = storeStocks.PreSuiteStock - matingTreeGrid.data.SuiteStock;
                                            //}

                                            //如果预配套数量 >= 工艺用量  并且 预配套数量
                                            if (preSuiteStock >= editParentData.Number)
                                            {
                                                storeStocks.UsableMatingQuantityStock = storeStocks.PreSuiteStock - matingTreeGrid.data.SuiteStock;
                                                //配套数量 = 配套数量+缺料数量 (因为肯定能配套成功)
                                                storeStocks.SuiteStock = storeStocks.SuiteStock + storeStocks.StarvingStock;
                                                storeStocks.StarvingStock = 0;
                                            }
                                            //如果预配套数量 < 工艺用量 
                                            else if (preSuiteStock < editParentData.Number && preSuiteStock > 0)
                                            {
                                                storeStocks.UsableMatingQuantityStock = storeStocks.PreSuiteStock - matingTreeGrid.data.SuiteStock;
                                                //配套数量 = 配套数量+可用预配套数量 （存在配套不成功的情况） 
                                                storeStocks.SuiteStock = storeStocks.SuiteStock + storeStocks.UsableMatingQuantityStock;
                                                storeStocks.StarvingStock = storeStocks.StarvingStock - storeStocks.UsableMatingQuantityStock;
                                            }
                                            else
                                            {

                                            }

                                            //出库数量 （查询时计算）
                                            storeStocks.DeliveryStock = matingTreeGrid.data.DeliveryStock;
                                            //如果可用数量等于0 缺料
                                            if (storeStocks.UsableMatingQuantityStock == 0 || storeStocks.UsableMatingQuantityStock < storeStocks.StarvingStock)
                                            {
                                                storeStocks.MatingStatus = (int)AssortStatus.缺料;
                                            }
                                            else if (storeStocks.UsableMatingQuantityStock >= storeStocks.StarvingStock)
                                            {
                                                storeStocks.MatingStatus = (int)AssortStatus.已配套;
                                            }
                                            //配套人 、配套时间、
                                            storeStocks.CompletePeople = userData.Surname + userData.Name;
                                            storeStocks.CompleteTime = DateTime.Now;
                                            //更新库存主表数据
                                            _storeStockRepsitory.UpdateAsync(storeStocks);
                                            #endregion
                                            #region 更新库存子表数据 
                                            //查出全部的已经预配套的零件 条件 已预配套、预配套id不等于null、配套id等于null 根据工艺用量取
                                            queryStoreStockConetnList = _storeStockContentRepsitory.GetAll().Where(c => c.StoreStockId == storeStocks.Id && c.IsPreSuit == IsSuits.是 && c.BomAnalysecontentId != null && c.LoadDetailsId == null).OrderBy(c => c.CreationTime).Take(matingTreeGrid.data.Number);
                                            //更新子表数据
                                            //加保险
                                            if (queryStoreStockConetnList.Count() > 0)
                                            {
                                                foreach (StoreStockContent storeStockContent in queryStoreStockConetnList)
                                                {
                                                    storeStockContent.LoadDetailsId = matingTreeGrid.data.LoadDetailsId;
                                                    storeStockContent.IsSuit = IsSuits.是;
                                                    storeStockContent.CompletePeople = userData.Surname + userData.Name;
                                                    storeStockContent.CompleteTime = DateTime.Now;
                                                    _storeStockContentRepsitory.UpdateAsync(storeStockContent);
                                                }
                                            }

                                            #endregion

                                            break;
                                        default:
                                            break;
                                    }
                                });
                            }
                        }
                        //针对于一级
                        else if (matingTreeGrid.children.Count == 0)
                        {
                            editParentData = matingTreeGrid.data;
                            var loadEntity = _loadPieceRepository.Get(matingTreeGrid.data.LoadDetailsId);
                            var collectCom = _collectBomManagerRepository.FirstOrDefaultAsync(t => t.ModuleId.ToString() == matingTreeGrid.data.HJXH && t.SendTimeId.ToString() == matingTreeGrid.data.HJFC && t.Id == matingTreeGrid.data.CollectId).Result;
                            string yerars = "";
                            if (editParentData.StoreStockId == Guid.Empty)
                            {
                                resultMessage.code = 1;
                                resultMessage.Message = "请选择已经预配套数据";
                                return resultMessage;
                            }
                            //根据配套状态 进行判断
                            switch (editParentData.MatingStatus)
                            {
                                case (int)AssortStatus.未配套:
                                    // 自动配套 手动配套

                                    #region 计算数量
                                    //根据id获取库存主表相关信息
                                    var storeStocks = _storeStockRepsitory.Get(editParentData.StoreStockId);
                                    //查出全部的已经预配套的零件 条件 已预配套、预配套id不等于null、配套id等于null 根据工艺用量取
                                    IQueryable<StoreStockContent> storeStockContents = null;
                                    if (matingTreeGrid.data.MaterialsTypeName == "零件")
                                    {
                                        storeStockContents = _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == storeStocks.Id && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.LoadDetailsId == null && t.BomAnalysecontentId == collectCom.Id).OrderBy(t => t.SendTimeLength).ThenByDescending(t => t.Years == yerars).ThenBy(t => t.CreationTime).Take(matingTreeGrid.data.Number);
                                    }
                                    else if (matingTreeGrid.data.MaterialsTypeName == "标准件")
                                    {

                                        //if (matingTreeGrid.data.Code.Split('-').Count() > 0)
                                        //{
                                        //    yerars = matingTreeGrid.data.Code.Split('-')[1];
                                        //}
                                        //string years = "";
                                        //var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectCom.XJId);
                                        //if (collectBomMaterialsContentDtos == null)
                                        //{
                                        //    return null;
                                        //}
                                        //var dyMaterils = collectBomMaterialsContentDtos.FirstOrDefault(t => t.MerialsId == loadEntity.MaterialsContentId);
                                        //if (dyMaterils != null)
                                        //{
                                        //    years = dyMaterils.YearsNo;
                                        //}
                                        yerars = "";
                                        if (matingTreeGrid.data.Code.Split('-').Length > 1)
                                        {
                                            int length = matingTreeGrid.data.Code.Split('-').Length;
                                            yerars = matingTreeGrid.data.Code.Split('-')[length - 1];
                                        }
                                        storeStockContents = _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == storeStocks.Id && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.LoadDetailsId == null && t.BomAnalysecontentId == collectCom.Id).OrderBy(t => t.SendTimeLength).ThenByDescending(t => yerars.Contains(t.Years)).ThenBy(t => t.CreationTime).ThenBy(t => t.CreationTime).Take(matingTreeGrid.data.Number);
                                    }
                                    //计算数量 更新库存信息主表数据
                                    //芯级预配套数量：设计bom的芯级预配套配套数量
                                    //可用预配套数量：芯级预配套数量-配套数量
                                    storeStocks.UsableMatingQuantityStock = matingTreeGrid.data.PreSuiteStock - matingTreeGrid.data.SuiteStock;
                                    //配套数量== 可用预配套数量
                                    if (storeStockContents != null)
                                    {
                                        storeStocks.SuiteStock = storeStockContents.Count();

                                        //缺料数量 工艺用量 -配套数量  
                                        storeStocks.StarvingStock = matingTreeGrid.data.Number - storeStocks.SuiteStock > 0 ? matingTreeGrid.data.Number - storeStocks.SuiteStock : 0;
                                        //出库数量 （查询时计算）
                                        storeStocks.DeliveryStock = matingTreeGrid.data.DeliveryStock;
                                        //工艺用量 -配套数量  > 可用预配套数量
                                        if (storeStocks.StarvingStock > matingTreeGrid.data.UsableMatingQuantityStock)
                                        {
                                            storeStocks.MatingStatus = (int)AssortStatus.缺料;
                                        }
                                        //工艺用量  =  配套数量
                                        else if (matingTreeGrid.data.Number == storeStocks.SuiteStock)
                                        {
                                            storeStocks.MatingStatus = (int)AssortStatus.已配套;
                                        }
                                        //工艺用量 - 配套数量  ≤ 可用预配套数量
                                        else if (storeStocks.StarvingStock <= storeStocks.UsableMatingQuantityStock)
                                        {
                                            storeStocks.MatingStatus = (int)AssortStatus.配套中;
                                        }
                                        else
                                        {
                                            storeStocks.MatingStatus = (int)AssortStatus.未配套;
                                        }
                                        //配套人 、配套时间、
                                        storeStocks.CompletePeople = userData.Surname + userData.Name;
                                        storeStocks.CompleteTime = DateTime.Now;

                                        #endregion
                                        #region 更新库存子表数据 
                                        //查出全部的已经预配套的零件 条件 已预配套、预配套id不等于null、配套id等于null 根据工艺用量取
                                        //var queryStoreStockConetnList = _storeStockContentRepsitory.GetAll().Where(t=>t.StoreStockId == storeStocks.Id && t.IsPreSuit == IsSuits.是 &&t.BomAnalysecontentId!=null&&t.LoadDetailsId==null).OrderBy(t=>t.CreationTime).ThenBy(t=>t.ProductNumber).Take(matingTreeGrid.data.Number);
                                        //更新子表数据
                                        //加保险
                                        if (storeStockContents.Count() > 0)
                                        {
                                            //更新库存主表数据
                                            _storeStockRepsitory.Update(storeStocks);

                                            foreach (StoreStockContent storeStockContent in storeStockContents)
                                            {
                                                storeStockContent.WorkStepId = loadEntity.WorkStepEntityId;
                                                storeStockContent.LoadDetailsId = matingTreeGrid.data.LoadDetailsId;
                                                storeStockContent.IsSuit = IsSuits.是;
                                                storeStockContent.CompletePeople = userData.Surname + userData.Name;
                                                storeStockContent.CompleteTime = DateTime.Now;
                                                _storeStockContentRepsitory.Update(storeStockContent);

                                            }
                                            _unitOfWorkManager.Current.SaveChanges();
                                        }
                                    }
                                    _iOperationHistoryAppService.InsertOperationLogNew(storeStocks.Id, BusinessTypes.工艺配套, OperationTypes.配套, "人工配套");
                                    #endregion
                                    break;
                                case (int)AssortStatus.配套中:

                                    #region 计算数量
                                    //根据id获取库存主表相关信息
                                    storeStocks = _storeStockRepsitory.Get(editParentData.StoreStockId);
                                    //计算数量 更新库存信息主表数据
                                    //芯级预配套数量：设计bom的芯级预配套配套数量
                                    // storeStocks.PreSuiteStock =
                                    //（预配套数量 -配套数量 ：计算可用数量）
                                    int sl = storeStocks.PreSuiteStock - matingTreeGrid.data.SuiteStock;

                                    //配套数量 += 可用预配套数量
                                    storeStocks.SuiteStock = matingTreeGrid.data.UsableMatingQuantityStock >= matingTreeGrid.data.Number ? matingTreeGrid.data.Number : 0;
                                    //可用预配套数量：预配套数量- 1
                                    storeStocks.UsableMatingQuantityStock = matingTreeGrid.data.PreSuiteStock - storeStocks.SuiteStock;
                                    //缺料数量 
                                    storeStocks.StarvingStock = 0;
                                    //出库数量 （查询时计算）
                                    storeStocks.DeliveryStock = matingTreeGrid.data.DeliveryStock;
                                    storeStocks.MatingStatus = (int)AssortStatus.已配套;
                                    ////工艺用量 -配套数量  > 可用预配套数量
                                    //if (storeStocks.StarvingStock > matingTreeGrid.data.UsableMatingQuantityStock)
                                    //{
                                    //    storeStocks.MatingStatus = (int)AssortStatus.缺料;
                                    //}
                                    ////工艺用量  =  配套数量
                                    //else if (matingTreeGrid.data.Number == storeStocks.SuiteStock)
                                    //{
                                    //    storeStocks.MatingStatus = (int)AssortStatus.已配套;
                                    //}
                                    ////工艺用量 - 配套数量  ≤ 可用预配套数量
                                    //else if (storeStocks.StarvingStock <= matingTreeGrid.data.UsableMatingQuantityStock)
                                    //{
                                    //    storeStocks.MatingStatus = (int)AssortStatus.配套中;
                                    //}
                                    //else
                                    //{
                                    //    storeStocks.MatingStatus = (int)AssortStatus.未配套;
                                    //}
                                    //配套人 、配套时间、
                                    storeStocks.CompletePeople = userData.Surname + userData.Name;
                                    storeStocks.CompleteTime = DateTime.Now;
                                    #endregion
                                    #region 更新库存子表数据 
                                    //查出全部的已经预配套的零件 条件 已预配套、预配套id不等于null、配套id等于null 根据工艺用量取
                                    IQueryable<StoreStockContent> queryStoreStockConetnList = null;
                                    if (matingTreeGrid.data.MaterialsTypeName == "零件")
                                    {
                                        queryStoreStockConetnList = _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == storeStocks.Id && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.LoadDetailsId == null && t.BomAnalysecontentId == collectCom.Id).OrderBy(t => t.SendTimeLength).ThenByDescending(t => t.Years == yerars).ThenBy(t => t.CreationTime).Take(matingTreeGrid.data.Number - matingTreeGrid.data.SuiteStock);
                                    }
                                    else if (matingTreeGrid.data.MaterialsTypeName == "标准件")
                                    {

                                        yerars = "";
                                        if (matingTreeGrid.data.Code.Split('-').Length > 1)
                                        {
                                            int length = matingTreeGrid.data.Code.Split('-').Length;
                                            yerars = matingTreeGrid.data.Code.Split('-')[length - 1];
                                        }
                                        //var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectCom.XJId);
                                        //if (collectBomMaterialsContentDtos == null)
                                        //{
                                        //    return null;
                                        //}
                                        //var dyMaterils = collectBomMaterialsContentDtos.FirstOrDefault(t => t.MerialsId == loadEntity.MaterialsContentId);
                                        //if (dyMaterils != null)
                                        //{
                                        //    years = dyMaterils.YearsNo;
                                        //}
                                        queryStoreStockConetnList = _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == storeStocks.Id && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.LoadDetailsId == null && t.BomAnalysecontentId == collectCom.Id).OrderBy(t => t.SendTimeLength).ThenByDescending(t => yerars.Contains(t.Years)).ThenBy(t => t.CreationTime).Take(matingTreeGrid.data.Number - matingTreeGrid.data.SuiteStock);
                                    }
                                    //更新子表数据
                                    //加保险
                                    if (queryStoreStockConetnList.Count() > 0)
                                    {
                                        //更新库存主表数据
                                        _storeStockRepsitory.Update(storeStocks);

                                        foreach (StoreStockContent storeStockContent in queryStoreStockConetnList)
                                        {
                                            storeStockContent.WorkStepId = loadEntity.WorkStepEntityId;
                                            storeStockContent.LoadDetailsId = matingTreeGrid.data.LoadDetailsId;
                                            storeStockContent.IsSuit = IsSuits.是;
                                            storeStockContent.CompletePeople = userData.Surname + userData.Name;
                                            storeStockContent.CompleteTime = DateTime.Now;
                                            _storeStockContentRepsitory.Update(storeStockContent);

                                        }
                                        _unitOfWorkManager.Current.SaveChanges();
                                    }

                                    #endregion
                                    _iOperationHistoryAppService.InsertOperationLogNew(storeStocks.Id, BusinessTypes.工艺配套, OperationTypes.配套, "自动配套");
                                    break;
                                case (int)AssortStatus.缺料:

                                    #region 计算数量
                                    //根据id获取库存主表相关信息
                                    storeStocks = _storeStockRepsitory.Get(editParentData.StoreStockId);
                                    //计算数量 更新库存信息主表数据
                                    //芯级预配套数量：设计bom的芯级预配套配套数量
                                    // storeStocks.PreSuiteStock =
                                    //预配套数量
                                    if (matingTreeGrid.data.PreSuiteStock != 0)
                                    {

                                        int preSuiteStock = matingTreeGrid.data.SuiteStock;
                                        //storeStocks.UsableMatingQuantityStock = storeStocks.PreSuiteStock - matingTreeGrid.data.SuiteStock;
                                        //如果预配套数量>=缺料数量  并且 预配套数量
                                        //if (preSuiteStock >= editParentData.StarvingStock)
                                        //{
                                        //    storeStocks.UsableMatingQuantityStock = storeStocks.PreSuiteStock - matingTreeGrid.data.SuiteStock;
                                        //}

                                        //如果预配套数量 >= 工艺用量  并且 预配套数量

                                        //如果预配套数量 < 工艺用量 


                                        // storeStocks.UsableMatingQuantityStock = storeStocks.PreSuiteStock - matingTreeGrid.data.SuiteStock;
                                        //配套数量 = 配套数量+可用预配套数量 （存在配套不成功的情况） 
                                        storeStocks.SuiteStock = matingTreeGrid.data.UsableMatingQuantityStock;
                                        //可用预配套数量 =0;因为预配套数量小于工艺用量 直接赋值为0 或者芯级用量-配套数量
                                        storeStocks.StarvingStock = matingTreeGrid.data.StarvingStock;



                                        storeStocks.UsableMatingQuantityStock = 0;

                                        //缺料数量还是等于原来的数量
                                        // storeStocks.StarvingStock = storeStocks.StarvingStock - storeStocks.UsableMatingQuantityStock;

                                        //出库数量 还是等于原来的出库数量
                                        //storeStocks.DeliveryStock = matingTreeGrid.data.DeliveryStock;
                                        //如果可用数量等于0 缺料 storeStocks.UsableMatingQuantityStock == 0 &&

                                        if (matingTreeGrid.data.StarvingStock != 0)
                                        {
                                            storeStocks.MatingStatus = (int)AssortStatus.缺料;
                                        }
                                        //缺料状态下不存在已配套的情况
                                        //else if (storeStocks.UsableMatingQuantityStock >= storeStocks.StarvingStock)
                                        //{
                                        //    storeStocks.MatingStatus = (int)AssortStatus.已配套;
                                        //}
                                        //配套人 、配套时间、
                                        storeStocks.CompletePeople = userData.Surname + userData.Name;
                                        storeStocks.CompleteTime = DateTime.Now;
                                        //更新库存主表数据

                                        #endregion
                                        #region 更新库存子表数据 
                                        //queryStoreStockConetnList = _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId ==  matingTreeGrid.data.StoreStockId && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.LoadDetailsId == null&&t.Batch=="01" && t.BomAnalysecontentId == collectCom.Id).OrderBy(t => t.CreationTime).ThenBy(t => t.ProductNumber).Take(storeStocks.SuiteStock);
                                        IQueryable<StoreStockContent> queryStoreStockSving = null;
                                        if (matingTreeGrid.data.MaterialsTypeName == "零件")
                                        {
                                            queryStoreStockSving = _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == matingTreeGrid.data.StoreStockId && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.LoadDetailsId == null && t.Batch == "01" && t.BomAnalysecontentId == collectCom.Id).OrderBy(t => t.SendTimeLength).ThenByDescending(t => t.Years == yerars).ThenBy(t => t.CreationTime).Take(storeStocks.SuiteStock);
                                        }
                                        else if (matingTreeGrid.data.MaterialsTypeName == "标准件")
                                        {
                                            yerars = "";
                                            if (matingTreeGrid.data.Code.Split('-').Length > 1)
                                            {
                                                int length = matingTreeGrid.data.Code.Split('-').Length;
                                                yerars = matingTreeGrid.data.Code.Split('-')[length - 1];
                                            }
                                            //string years = "";
                                            //var collectBomMaterialsContentDtos = _collectBomAppService.GetCollectBomMaterialsContent(collectCom.XJId);
                                            //if (collectBomMaterialsContentDtos == null)
                                            //{
                                            //    return null;
                                            //}
                                            //var dyMaterils = collectBomMaterialsContentDtos.FirstOrDefault(t => t.MerialsId == loadEntity.MaterialsContentId);
                                            //if (dyMaterils != null)
                                            //{
                                            //    years = dyMaterils.YearsNo;
                                            //}

                                            queryStoreStockSving = _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == matingTreeGrid.data.StoreStockId && t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.LoadDetailsId == null && t.Batch == "01" && t.BomAnalysecontentId == collectCom.Id).OrderBy(t => t.SendTimeLength).ThenByDescending(t => yerars.Contains(t.Years)).ThenBy(t => t.CreationTime).Take(storeStocks.SuiteStock);
                                        }


                                        //更新子表数据
                                        //加保险
                                        if (queryStoreStockSving.Count() > 0)
                                        {
                                            _storeStockRepsitory.Update(storeStocks);

                                            foreach (StoreStockContent storeStockContent in queryStoreStockSving)
                                            {
                                                storeStockContent.WorkStepId = loadEntity.WorkStepEntityId;
                                                storeStockContent.LoadDetailsId = matingTreeGrid.data.LoadDetailsId;
                                                storeStockContent.IsSuit = IsSuits.是;
                                                storeStockContent.CompletePeople = userData.Surname + userData.Name;
                                                storeStockContent.CompleteTime = DateTime.Now;
                                                _storeStockContentRepsitory.Update(storeStockContent);

                                            }
                                            _unitOfWorkManager.Current.SaveChanges();

                                        }
                                        #endregion
                                    }

                                    _iOperationHistoryAppService.InsertOperationLogNew(storeStocks.Id, BusinessTypes.工艺配套, OperationTypes.配套, "自动配套");
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary> 
        /// 包含已经配套 和预配套的  这个接口针对于解配套的外部调用
        /// </summary>
        /// <param name="guidList"></param>
        /// <returns></returns>
        public async Task<ResultMessage> ExteriorRelieveMating(List<StoreStockContent> storeStockContents)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                if (storeStockContents.Count > 0)
                {
                    List<StoreStockContent> stockContent = new List<StoreStockContent>();
                    //查出库存主表数据
                    var storeStockContentList = _storeStockRepsitory.FirstOrDefaultAsync(t => t.Id == storeStockContents[0].StoreStockId && t.StoreId == storeStockContents[0].StoreId).Result;
                    var storeStockContentCount = _storeStockContentRepsitory.Count(t => t.StoreStockId == storeStockContentList.Id && t.StoreId == storeStockContentList.StoreId && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId != null);
                    if (storeStockContentList != null)
                    {
                        //更新子表数据
                        foreach (StoreStockContent storeStockContent in storeStockContents)
                        {
                            //if (!storeStockContent.Id.ToString().Contains(joinId))
                            //{
                            storeStockContent.IsSuit = IsSuits.否;
                            storeStockContent.LoadDetailsId = null;
                            storeStockContent.WorkStepId = null;
                            storeStockContent.CompletePeople = null;
                            storeStockContent.CompleteTime = null;
                            stockContent.Add(storeStockContent);
                            //}
                        }
                        if (stockContent.Count > 0)
                        {
                            foreach (StoreStockContent content in stockContent)
                            {
                                await _storeStockContentRepsitory.UpdateAsync(content);
                            }
                        }
                        storeStockContentList.CompleteTime = null;
                        storeStockContentList.CompletePeople = null;
                        //storeStockContentList.UsableMatingQuantityStock += storeStockContents.Count == 0 ? storeStockContents.Count + 1 : storeStockContentList.SuiteStock - storeStockContents.Count;
                        storeStockContentList.UsableMatingQuantityStock += storeStockContents.Count;
                        storeStockContentList.SuiteStock -= storeStockContents.Count;
                        if (storeStockContentCount > storeStockContents.Count)
                        {
                            storeStockContentList.MatingStatus = (int)AssortStatus.配套中;
                        }
                        else
                        {
                            storeStockContentList.MatingStatus = (int)AssortStatus.未配套;
                        }
                        var listNew = ObjectMapper.Map<StoreStock>(storeStockContentList);
                        await _storeStockRepsitory.UpdateAsync(listNew);
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 解配套
        /// </summary>
        /// <param name="matingTreeGridDto"></param>
        /// <returns></returns>
        public async Task<ResultMessage> RelieveMating(List<MatingTreeGridDto> matingTreeGridDto)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                if (matingTreeGridDto.Count > 0)
                {
                    foreach (MatingTreeGridDto matingTreeGrid in matingTreeGridDto)
                    {
                        if (matingTreeGrid.children.Count == 0)
                        {
                            //找出库存主表信息
                            var storeStockContentList = _storeStockRepsitory.GetAll().Where(t => t.Id == matingTreeGrid.data.StoreStockId);
                            //去除库存子表的 预配套状态 和 占用id 更新 条件 ：
                            var storeStockList = (from storeStock in storeStockContentList
                                                  join storeStockContent in _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == matingTreeGrid.data.StoreStockId && t.IsSuit == IsSuits.是 && t.IsPreSuit == IsSuits.是 && t.LoadDetailsId != null && t.BomAnalysecontentId != null && t.BomAnalysecontentId == matingTreeGrid.data.CollectId) on storeStock.Id equals storeStockContent.StoreStockId
                                                  // where matingTreeGrid.data.ProductNumber.Contains(storeStockContent.ProductNumber)
                                                  select storeStockContent).OrderBy(t => t.CreationTime);
                            var querystoreStockList = storeStockList.WhereIf(matingTreeGrid.data.WorkStepId != Guid.Empty || matingTreeGrid.data.WorkStepId != null, t => t.WorkStepId == matingTreeGrid.data.WorkStepId && t.LoadDetailsId == matingTreeGrid.data.LoadDetailsId);
                            if (querystoreStockList.Count() == 0)
                            {
                                continue;
                            }
                            foreach (StoreStockContent storeStockContent in querystoreStockList)
                            {
                                //storeStockContent.BomAnalysecontentId = null;
                                //storeStockContent.IsPreSuit = IsSuits.否;

                                storeStockContent.IsSuit = IsSuits.否;
                                storeStockContent.LoadDetailsId = null;
                                storeStockContent.WorkStepId = null;
                                storeStockContent.CompletePeople = null;
                                storeStockContent.CompleteTime = null;
                                await _storeStockContentRepsitory.UpdateAsync(storeStockContent);
                            }
                            //更新库存主表的数量 
                            //库存主表的 数量 需要更改哪些？ 1：可用预配套数量 2：预配套数量 3：自由库存数量 
                            foreach (StoreStock store in storeStockContentList)
                            {
                                //可用预配套数量
                                //store.UsableMatingQuantityStock += matingTreeGrid.data.SuiteStock;
                                //配套数量为0
                                store.SuiteStock = 0;
                                //store.PreSuiteStock += 0;
                                //store.FreeQuantityStock += store.PreSuiteStock;
                                store.CompletePeople = null;
                                store.CompleteTime = null;
                                store.CompletePeople = null;
                                store.CompleteTime = null;
                                await _storeStockRepsitory.UpdateAsync(store);
                                _iOperationHistoryAppService.InsertOperationLogNew(store.Id, BusinessTypes.设计BOM预配套分析, OperationTypes.配套, "解除配套");
                            }
                        }
                        else
                        {
                            if (matingTreeGrid.children.Count > 0)
                            {
                                List<MatingDetaillist> matingDetaillist = matingTreeGrid.children;
                                if (matingDetaillist.Count() > 0)
                                {
                                    foreach (MatingDetaillist detaillist in matingDetaillist)
                                    {
                                        //有子级 针对于含有父级的
                                        if (matingTreeGrid.children.Count > 0)
                                        {
                                            //找出库存主表信息
                                            var storeStockContentList = _storeStockRepsitory.GetAll().Where(t => t.Id == detaillist.data.StoreStockId);
                                            //去除库存子表的 预配套状态 和 占用id 更新 条件 ：
                                            var storeStockList = (from storeStock in storeStockContentList
                                                                  join storeStockContent in _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == detaillist.data.StoreStockId && t.IsSuit == IsSuits.是 && t.IsPreSuit == IsSuits.是 && t.LoadDetailsId != null && t.BomAnalysecontentId != null) on storeStock.Id equals storeStockContent.StoreStockId
                                                                  //  where storeStockContent.ProductNumber.Contains(storeStockContentList.ToList()[0].ProductNumber)
                                                                  select storeStockContent).OrderBy(t => t.CreationTime);
                                            foreach (StoreStockContent storeStockContent in storeStockList)
                                            {
                                                //storeStockContent.BomAnalysecontentId = null;
                                                //storeStockContent.IsPreSuit = IsSuits.否;
                                                storeStockContent.IsSuit = IsSuits.否;
                                                storeStockContent.LoadDetailsId = null;
                                                storeStockContent.WorkStepId = null;
                                                storeStockContent.CompletePeople = null;
                                                storeStockContent.CompleteTime = null;
                                                await _storeStockContentRepsitory.UpdateAsync(storeStockContent);
                                            }
                                            //更新库存主表的数量 
                                            //库存主表的 数量 需要更改哪些？ 1：可用预配套数量 2：预配套数量 3：自由库存数量 
                                            foreach (StoreStock store in storeStockContentList)
                                            {
                                                //可用预配套数量
                                                store.UsableMatingQuantityStock += detaillist.data.SuiteStock;
                                                //配套数量为0
                                                store.SuiteStock = 0;
                                                store.CompletePeople = null;
                                                store.CompleteTime = null;
                                                //store.PreSuiteStock += 0;
                                                //store.FreeQuantityStock += store.PreSuiteStock;
                                                await _storeStockRepsitory.UpdateAsync(store);
                                                _iOperationHistoryAppService.InsertOperationLogNew(store.Id, BusinessTypes.设计BOM预配套分析, OperationTypes.配套, "解除配套");
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 导出配套表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> GetBomMatingToExcel(List<MatingTreeGridDto> matingTreeGrids)
        {
            List<MatingTreeGridDto> matingTreeGridList = new List<MatingTreeGridDto>();
            List<MatingEditParentData> parentData = new List<MatingEditParentData>();
            //List<object>   matingEditChildData = new List<object>();
            List<object> all = new List<object>();
            foreach (MatingTreeGridDto treeGridDto in matingTreeGrids)
            {
                treeGridDto.data.LevelNum = 1;
                //parentData.Clear();
                parentData.Add(treeGridDto.data);
                if (treeGridDto.children.Count() > 0)
                {
                    foreach (MatingDetaillist matingDetaillist in treeGridDto.children)
                    {
                        matingDetaillist.data.LevelNum = 2;
                        matingDetaillist.data.PreSuiteTime = DateTime.Parse(matingDetaillist.data.PreSuiteTime).ToString("yyyy-MM-dd HH:mm:ss");
                        matingDetaillist.data.CompleteTime = DateTime.Parse(matingDetaillist.data.CompleteTime).ToString("yyyy-MM-dd HH:mm:ss");
                        parentData.Add(ObjectMapper.Map<MatingEditParentData>(matingDetaillist.data));
                    }
                }
            }
            return _bomMatingExportToExcelRepository.ExportToFile(parentData, 2);
        }
        /// <summary>
        /// 根据规程id导出
        /// </summary>
        /// <param name="techId">节点id</param>
        /// <returns></returns>
        public async Task<string> GetBomMatingToExcelById(Guid nodeId)
        {
            var bopNode = _bopNodeRepository.Get(nodeId);
            var techId = bopNode.TechniqueEntityId;
            var queryStoreStockContent = from storeStockContent in _storeStockContentRepsitory.GetAll() select storeStockContent;
            //获取工序和工步的信息，并做相应的排序
            var processesList = _processesEntityRepository.GetAllIncluding(p => p.WorkStepEntities).Where(p => p.TechniqueEntityId == techId).OrderBy(n => n.ProcessesSequence).ToList();
            processesList.ToList().ForEach(q => q.WorkStepEntities = q.WorkStepEntities.OrderBy(r => r.WorkStepNumber).ToList());
            for (int i = 0; i < processesList.ToList().Count; i++)
            {
                int index = i + 1;
                MatingEditParentData tree = new MatingEditParentData();
                tree.Id = processesList[i].Id;
                //  tree.ParentId = techId.Value;
                tree.Code = "工序" + processesList[i].ProcessesSequence.ToString() + " ";
                tree.Name = processesList[i].ProcessesName;
                //  tree.IsRelation = 0;
                tree.NodeLevel = 8;
                //       tree.OutboundStatusDesc = GetEnumDesc(processesList[i].OutboundState);
                // tree.LevelRelationship = LevelString + "." + index;
                tree.LevelNum = 1;
                bomMakeEditChildDatas.Add(tree);
                //查询工步
                List<WorkStepEntity> workStepEntities = processesList[i].WorkStepEntities.ToList();
                for (int k = 0; k < workStepEntities.Count; k++)
                {
                    int indexTwo = k + 1;
                    MatingEditParentData wtree = new MatingEditParentData();
                    wtree.Id = workStepEntities[k].Id;
                    //    wtree.ParentId = processesList[i].Id;
                    wtree.Code = "工步" + workStepEntities[k].WorkStepNumber.ToString();// + "-"+ witem.WorkStepNumber.ToString();
                    wtree.Name = workStepEntities[k].WorkStepNumber.ToString();//witem.WorkStepName  这个值数据库有问题
                                                                               //    wtree.IsRelation = 0;
                    wtree.NodeLevel = 9;
                    //     wtree.OutboundStatusDesc = GetEnumDesc(workStepEntities[k].OutboundState);
                    // wtree.data.LevelRelationship = tree.data.LevelRelationship + "." + indexTwo;
                    wtree.LevelNum = 2;
                    bomMakeEditChildDatas.Add(wtree);
                    PartsOutboundInput partsOutboundInput = new PartsOutboundInput();
                    partsOutboundInput.NodeId = workStepEntities[k].Id;
                    MatingTreeResult matingTreeResult = DisplayMatingNodeDetails(partsOutboundInput);
                    foreach (MatingTreeGridDto matingTreeGridDto in matingTreeResult.MatingTreeGridList)
                    {
                        if (matingTreeGridDto.data.StoreStockId != Guid.Empty && matingTreeGridDto.data.WorkStepId != Guid.Empty && matingTreeGridDto.data.LoadDetailsId != Guid.Empty && matingTreeGridDto.data.CollectId != Guid.Empty)
                        {
                            //计算工步下对应的子表配套信息
                            List<StoreStockContentDto> storeStockContentDtos = await GetExecuteMatingPreSuitePerson(matingTreeGridDto.data.StoreStockId, matingTreeGridDto.data.WorkStepId.Value, matingTreeGridDto.data.LoadDetailsId, matingTreeGridDto.data.CollectId.Value);
                            if (storeStockContentDtos.Count > 0)
                            {
                                matingTreeGridDto.data.LevelNum = 3;
                                matingTreeGridDto.data.StoreContents = new List<StoreStockContentDto>();
                                matingTreeGridDto.data.StoreContents.AddRange(storeStockContentDtos);
                            }
                            bomMakeEditChildDatas.Add(matingTreeGridDto.data);
                            //根据工步下的子表的配套 关联主表配套信息
                            //var querycalcCount = from matingTreeGuidListData in matingTreeResult.MatingTreeGridList
                            //                     join storkStoreContentData in storeStockContentDtos.Where(t => t.IsSuit == (int)IsSuits.是 && t.LoadDetailsId != null && t.IsPreSuit == (int)IsSuits.是 && t.BomAnalysecontentId != null) on matingTreeGuidListData.data.StoreStockId equals storkStoreContentData.StoreStockId
                            //                     select matingTreeGuidListData;

                            ////三种情况： 1 合格证号 无  、放行单号 有  2 反之 3 合格证号有 放行单号有 取 合格证号  

                            //// 1 根据 StoreStockId QualifiedNumber 分组 合并 ProductNumber 
                            //var queryProduct = from matingAll in querycalcCount
                            //                   group matingAll by new { matingAll.StoreStockId, matingAll.QualifiedNumber } into materialsAll
                            //                   select new
                            //                   {
                            //                       StoreStockId = materialsAll.Key.StoreStockId,
                            //                       //组合物料编号
                            //                       ProductNumberJoin = string.Join("@", materialsAll.Select(x => x.ProductNumber).Distinct()),
                            //                       //物料编号个数
                            //                      ProductNumberJoinCount = querycalcCount.Count(t=>t.StoreStockId == materialsAll.Key.StoreStockId&&t.QualifiedNumber == materialsAll.Key.QualifiedNumber&&t.ProductNumber!=null)
                            //                   };
                            ////2 根据 StoreStockId ReleaseOrder 分组 合并 ProductNumber 
                            //var queryProductOrder = from matingAll in querycalcCount
                            //                   group matingAll by new { matingAll.StoreStockId, matingAll.ReleaseOrder } into materialsAll
                            //                   select new
                            //                   {
                            //                       StoreStockId = materialsAll.Key.StoreStockId,
                            //                       //组合物料编号
                            //                       ProductNumberJoin = string.Join("@", materialsAll.Select(x => x.ProductNumber).Distinct()),
                            //                       //物料编号个数
                            //                       ProductNumberJoinCount = querycalcCount.Count(t => t.StoreStockId == materialsAll.Key.StoreStockId && t.ReleaseOrder == materialsAll.Key.ReleaseOrder && t.ProductNumber != null)
                            //                   };



                            //var queryUnion = from matingAll in querycalcCount
                            //                 group matingAll by new { matingAll.StoreStockId } into materialsAll
                            //                 select new
                            //                 {
                            //                     StoreStockId = materialsAll.Key.StoreStockId,
                            //                     //合格证号
                            //                     QualifiedNumber = string.Join("@", materialsAll.Select(x => x.QualifiedNumber).Distinct()),
                            //                     //合格证号数量
                            //                     QualifiedNumberCount = string.Join(",", materialsAll.Select(x => x.QualifiedNumber).Distinct()).Split(',').Length,
                            //                     //放行单号
                            //                     ReleaseOrder = string.Join(",", materialsAll.Select(x => x.ReleaseOrder).Distinct()),
                            //                     //放行单数量
                            //                     ReleaseOrderCount = string.Join(",", materialsAll.Select(x => x.ReleaseOrder).Distinct()).Split(',').Length,
                            //                     //产品编号
                            //                     ProductNumber = string.Join(",", materialsAll.Select(x => x.ProductNumber).Distinct()),
                            //                 };


                            //if (querycalcCount != null)
                            //{
                            //    var queryJoinAll = from matingTreeGuidListData in matingTreeResult.MatingTreeGridList
                            //                           //join unionData in querycalcCount on matingTreeGuidListData.data.StoreStockId equals unionData.StoreStockId
                            //                       select new MatingEditParentData
                            //                       {
                            //                           LevelNum = 3,
                            //                           Code = matingTreeGuidListData.data.Code,
                            //                           Name = matingTreeGuidListData.data.Name,
                            //                           Module = matingTreeGuidListData.data.Module,
                            //                           MaterialsTypeName = matingTreeGuidListData.data.MaterialsTypeName,
                            //                           Unit = matingTreeGuidListData.data.Unit,
                            //                           Number = matingTreeGuidListData.data.Number,
                            //                           PreSuiteStock = matingTreeGuidListData.data.PreSuiteStock,
                            //                           UsableMatingQuantityStock = matingTreeGuidListData.data.UsableMatingQuantityStock,
                            //                           SuiteStock = matingTreeGuidListData.data.SuiteStock,
                            //                           StarvingStock = matingTreeGuidListData.data.StarvingStock,
                            //                           DeliveryStock = matingTreeGuidListData.data.DeliveryStock,
                            //                           MatingStatusName = matingTreeGuidListData.data.MatingStatusName,
                            //                           CompletePeople = matingTreeGuidListData.data.CompletePeople,
                            //                           CompleteTime = matingTreeGuidListData.data.CompleteTime,
                            //                           PreSuiteName = matingTreeGuidListData.data.PreSuiteName,
                            //                           PreSuiteTime = matingTreeGuidListData.data.PreSuiteTime,
                            //                           //StoreStockId = unionData.StoreStockId,
                            //                           //QualifiedNumber = unionData.QualifiedNumber,
                            //                           //ReleaseOrder = unionData.ReleaseOrder,
                            //                           //ProductNumber = unionData.ProductNumber,
                            //                           //AllNumber = unionData.QualifiedNumberCount + "," + unionData.ReleaseOrderCount,
                            //                           JoinText = JoinText(matingTreeGuidListData.data.StoreStockId, matingTreeGuidListData.data.WorkStepId.Value, matingTreeGuidListData.data.LoadDetailsId, matingTreeGuidListData.data.CollectId.Value, storeStockContentDtos)
                            //                       };

                            //    break;
                            //}
                        }
                        else
                        {
                            matingTreeGridDto.data.LevelNum = 3;
                            bomMakeEditChildDatas.Add(matingTreeGridDto.data);
                        }


                    }
                    if (bomMakeEditChildDatas.Count > 0)
                    {
                        bomMakeEditChildDatas.ForEach(t =>
                        {
                            if (t.StoreContents != null && t.StoreContents.Count > 0)
                            {
                                t.JoinText = JoinText(t.StoreStockId, t.WorkStepId.Value, t.LoadDetailsId, t.CollectId.Value, t.StoreContents);
                            }
                        });
                    }
                }
            }
            return _bomMatingExportToExcelRepository.ExportToFile(bomMakeEditChildDatas, 3);
        }

        public string JoinText(Guid storeStockId, Guid workStepId, Guid loadEntityId, Guid collBomId, List<StoreStockContentDto> storeStockContentDtosList)
        {
            string joinText = "";
            List<StoreStockContentDto> storeStockContentDtos = storeStockContentDtosList.Where(t => t.StoreStockId == storeStockId && t.IsSuit == (int)IsSuits.是 && t.LoadDetailsId != null).ToList();
            if (storeStockContentDtos.Count() > 0)
            {
                var query = storeStockContentDtos.GroupBy(a => new { ProductNumber = a.ProductNumber == null ? "空" : a.ProductNumber, QualifiedNumber = a.QualifiedNumber == null ? "空" : a.QualifiedNumber, ReleaseOrder = a.ReleaseOrder == null ? "空" : a.ReleaseOrder })
                    .Select(s => new
                    {
                        ProductNumber = s.First().ProductNumber,
                        QualifiedNumber = s.First().QualifiedNumber,
                        ReleaseOrder = s.First().ReleaseOrder,
                        Count = s.Count()
                    });
                int i = 1;
                //foreach (StoreStockContentDto storeStockContentDto in storeStockContentDtos)
                foreach (var item in query)
                {
                    //joinText += "(" + (i++) + ")" + "：产品编码：" + (storeStockContentDto.ProductNumber == null ? "空" : storeStockContentDto.ProductNumber) + " ，合格证号：" + (storeStockContentDto.QualifiedNumber == null ? "空" : storeStockContentDto.QualifiedNumber) + "，放行单号：" + (storeStockContentDto.ReleaseOrder == null ? "空" : storeStockContentDto.ReleaseOrder) + "\r\n";
                    joinText += "(" + (i++) + ")" + "：产品编码：" + item.ProductNumber + " ，合格证号：" + item.QualifiedNumber + "，放行单号：" + item.ReleaseOrder + "数量：" + item.Count + "\r\n";
                }
                return joinText;
            }
            return joinText;
        }
        /// <summary>
        /// 人工配套
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> CompletePerson(MatingEditChildData input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var userDataList = _userRepository.FirstOrDefaultAsync(t => t.Id == GetCurrentUser().Id).Result; //add 11/30
                if (input != null)
                {
                    //根据id获取库存主表相关信息
                    var loadEntity = _loadPieceRepository.Get(input.LoadDetailsId);
                    List<StoreStockContentDto> StoreStockContentDto = input.StoreContents;
                    List<StoreStockContent> stockContent = new List<StoreStockContent>();

                    //var storeStocks = _storeStockRepsitory.Get(input.StoreContents[0].StoreStockId);
                    //先查出当前库存主表数据
                    var queryStoreStockList = _storeStockRepsitory.FirstOrDefaultAsync(t => t.Id == input.StoreStockId).Result;
                    //找出库存信息子表数据 已配套的数据
                    var queryStoreStockContentList = _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == queryStoreStockList.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId == input.WorkStepId && t.LoadDetailsId == input.LoadDetailsId);
                    //找出库存信息已配套的条数
                    var queryStoreStockContentCount = _storeStockContentRepsitory.Count(t => t.StoreStockId == queryStoreStockList.Id && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId == input.WorkStepId && t.LoadDetailsId == input.LoadDetailsId);
                    var notComplete = input.StoreContents.Where(t => t.IsSuit == (int)IsSuits.否 && t.LoadDetailsId == null);
                    //if () 
                    //{

                    //}
                    //如果 已配套的数量 大于 选择的数量 = 解配套  否则是配套   已预配套的数量 等于 选择的数量  =配套||解配套
                    if (input.Number < input.StoreContents.Count)
                    {
                        resultMessage.code = 1;
                        resultMessage.Message = "配套数量大于工艺用量，请检查！";
                        return resultMessage;
                        //throw new UserFriendlyException("配套数量大于工艺用量，请检查！");
                    }
                    if (queryStoreStockContentCount >= StoreStockContentDto.Count())
                    {

                        if (StoreStockContentDto.Count == 0)
                        {
                            // && input.ProductNumber.Contains(t.ProductNumber)
                            var queryStoreStockContentResult = _storeStockContentRepsitory.GetAll().Where(t => t.StoreStockId == input.StoreStockId && t.IsSuit == IsSuits.是 && t.LoadDetailsId != null && t.WorkStepId == input.WorkStepId && t.LoadDetailsId == input.LoadDetailsId);
                            foreach (StoreStockContent storeStockContent in queryStoreStockContentResult)
                            {
                                storeStockContent.IsSuit = IsSuits.否;
                                storeStockContent.LoadDetailsId = null;
                                storeStockContent.DesignatedModule = null;
                                storeStockContent.DesignatedSendTime = null;
                                storeStockContent.WorkStepId = null;
                                storeStockContent.CompletePeople = null;
                                storeStockContent.CompleteTime = null;
                                stockContent.Add(storeStockContent);
                            }
                        }
                        else
                        {
                            string joinId = string.Join(",", input.StoreContents.Select(t => t.Id));
                            //更新子表数据
                            foreach (StoreStockContent storeStockContent in queryStoreStockContentList.ToList())
                            {

                                if (!joinId.Contains(storeStockContent.Id.ToString()))
                                {
                                    storeStockContent.IsSuit = IsSuits.否;
                                    storeStockContent.LoadDetailsId = null;
                                    storeStockContent.CompletePeople = null;
                                    storeStockContent.CompleteTime = null;
                                    storeStockContent.WorkStepId = null;
                                    storeStockContent.CompletePeople = null;
                                    storeStockContent.CompleteTime = null;
                                    stockContent.Add(storeStockContent);
                                }
                            }
                        }
                        if (stockContent.Count > 0)
                        {
                            foreach (StoreStockContent content in stockContent)
                            {
                                if (content.OutboundState == OutboundStates.出库 || content.OutboundState == OutboundStates.未领料)
                                {
                                    resultMessage.code = 1;
                                    resultMessage.Message = "包含已出库和未领料的物料不能解配套";
                                    return resultMessage;
                                }
                                await _storeStockContentRepsitory.UpdateAsync(content);
                            }
                        }
                        else
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = "选择的物料不是该工步下的配套数据";
                            return resultMessage;
                        }
                        queryStoreStockList.CompleteTime = null;
                        queryStoreStockList.CompletePeople = null;
                        //input.StoreContents.Count == 0 ? input.StoreContents.Count + 1 : 
                        queryStoreStockList.UsableMatingQuantityStock = input.UsableMatingQuantityStock + stockContent.Count;
                        queryStoreStockList.SuiteStock = input.StoreContents.Count;
                        //queryStoreStockList.FreeQuantityStock = queryStoreStockContentCount - input.StoreContents.Count;
                        if (input.StarvingStock != 0)
                        {
                            queryStoreStockList.MatingStatus = (int)AssortStatus.缺料;
                        }
                        else
                        {
                            if (input.Number - queryStoreStockList.SuiteStock <= queryStoreStockList.UsableMatingQuantityStock && queryStoreStockList.SuiteStock != 0)
                            {
                                queryStoreStockList.MatingStatus = (int)AssortStatus.配套中;
                            }
                            else if (input.Number - queryStoreStockList.SuiteStock == input.Number && queryStoreStockList.SuiteStock == 0)
                            {
                                queryStoreStockList.MatingStatus = (int)AssortStatus.未配套;
                            }
                        }
                        var listNew = ObjectMapper.Map<StoreStock>(queryStoreStockList);
                        await _storeStockRepsitory.UpdateAsync(listNew);
                    }
                    else
                    {

                        switch (input.MatingStatus)
                        {
                            case (int)AssortStatus.未配套:
                                #region 计算数量
                                //计算数量 更新库存信息主表数据
                                //芯级预配套数量：设计bom的芯级预配套配套数量
                                //配套数量
                                queryStoreStockList.SuiteStock += notComplete.Count();
                                //可用预配套他数量
                                queryStoreStockList.UsableMatingQuantityStock = input.UsableMatingQuantityStock - notComplete.Count();
                                //缺料数量  工艺用量 -芯级预配套数量input.Number <= input.PreSuiteStock ? 0 : input.Number - input.PreSuiteStock
                                queryStoreStockList.StarvingStock = input.StarvingStock;
                                //出库数量 （查询时计算）
                                queryStoreStockList.DeliveryStock = input.DeliveryStock;
                                //工艺用量 -配套数量  > 可用预配套数量
                                if (queryStoreStockList.StarvingStock != 0)
                                {
                                    queryStoreStockList.MatingStatus = (int)AssortStatus.缺料;
                                    queryStoreStockList.CompletePeople = null;
                                    queryStoreStockList.CompleteTime = null;
                                }
                                //工艺用量  =  配套数量
                                else if (queryStoreStockList.StarvingStock == 0 && input.Number == queryStoreStockList.SuiteStock)
                                {
                                    queryStoreStockList.MatingStatus = (int)AssortStatus.已配套;
                                    queryStoreStockList.CompletePeople = userDataList.Surname + userDataList.Name;
                                    queryStoreStockList.CompleteTime = DateTime.Now;
                                }
                                //工艺用量 - 配套数量  ≤ 可用预配套数量
                                else if (queryStoreStockList.StarvingStock <= queryStoreStockList.UsableMatingQuantityStock)
                                {
                                    queryStoreStockList.MatingStatus = (int)AssortStatus.配套中;
                                    queryStoreStockList.CompletePeople = null;
                                    queryStoreStockList.CompleteTime = null;
                                }
                                //配套人 、配套时间、

                                //更新库存主表数据
                                await _storeStockRepsitory.UpdateAsync(queryStoreStockList);
                                _iOperationHistoryAppService.InsertOperationLogNew(queryStoreStockList.Id, BusinessTypes.设计BOM预配套分析, OperationTypes.人工配套, "人工配套");
                                #endregion

                                break;
                            case (int)AssortStatus.配套中:
                                //有两种状态 、配套完成、配套中
                                #region 计算数量
                                //计算数量 更新库存信息主表数据
                                //芯级预配套数量：设计bom的芯级预配套配套数量
                                //可用预配套数量(查询算出) :可用预配套数量 -选择子物料的数量
                                queryStoreStockList.UsableMatingQuantityStock = queryStoreStockList.UsableMatingQuantityStock - notComplete.Count();
                                //配套数量 =配套数量+选择子物料的数量
                                queryStoreStockList.SuiteStock += notComplete.Count();
                                //缺料数量 （查询时算出）
                                queryStoreStockList.StarvingStock = 0;
                                //出库数量 （查询时计算）
                                queryStoreStockList.DeliveryStock = input.DeliveryStock;
                                if (queryStoreStockList.SuiteStock < input.Number)
                                {
                                    queryStoreStockList.MatingStatus = (int)AssortStatus.配套中;
                                }
                                else if (queryStoreStockList.SuiteStock == input.Number)
                                {
                                    queryStoreStockList.MatingStatus = (int)AssortStatus.已配套;
                                }

                                //配套人 、配套时间、
                                queryStoreStockList.CompletePeople = userDataList.Surname + userDataList.Name;
                                queryStoreStockList.CompleteTime = DateTime.Now;
                                //更新库存主表数据
                                await _storeStockRepsitory.UpdateAsync(queryStoreStockList);
                                _iOperationHistoryAppService.InsertOperationLogNew(queryStoreStockList.Id, BusinessTypes.设计BOM预配套分析, OperationTypes.人工配套, "人工配套");
                                #endregion
                                break;
                            //缺料时证明可用数量为0 无须处理
                            case (int)AssortStatus.缺料:
                                break;
                            default:
                                break;
                        }
                        #region 更新库存子表数据 
                        foreach (StoreStockContentDto storeStockContent in notComplete)
                        {
                            var queryStoreStockContent = _storeStockContentRepsitory.FirstOrDefaultAsync(t => t.Id == storeStockContent.Id).Result;
                            queryStoreStockContent.LoadDetailsId = input.LoadDetailsId;
                            queryStoreStockContent.WorkStepId = loadEntity.WorkStepEntityId;
                            queryStoreStockContent.CompletePeople = userDataList.Surname + userDataList.Name;
                            queryStoreStockContent.CompleteTime = DateTime.Now;
                            //storeStocklist.WorkStepId =
                            queryStoreStockContent.IsSuit = IsSuits.是;
                            await _storeStockContentRepsitory.UpdateAsync(queryStoreStockContent);
                        }
                        #endregion
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 查询人工预配套信息
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<List<StoreStockContentDto>> GetExecuteMatingPreSuitePerson(Guid guid, Guid collid, Guid loadEntityId, Guid collBomId)
        {
            var userData = _userRepository.GetAll().ToList();
            //查出库存子表的相关数据||(t.IsSuit ==IsSuits.是 && t.LoadDetailsId!=null)
            var querybomAnalyseContent = from storeStock in _storeStockRepsitory.GetAll().Where(t => t.Id == guid)
                                         join storeStockContent in _storeStockContentRepsitory.GetAll().Where(t => (t.IsPreSuit == IsSuits.是 && t.BomAnalysecontentId != null && t.LoadDetailsId == null && t.BomAnalysecontentId == collBomId) || (t.LoadDetailsId
                                         != null && t.IsSuit == IsSuits.是 && t.WorkStepId == collid && t.LoadDetailsId == loadEntityId)) on storeStock.Id equals
                                         storeStockContent.StoreStockId
                                         join storePutContent in _storePutContentRepository.GetAll() on storeStockContent.StorePutContentId equals storePutContent.Id
                                         join materialsContent in _materialsContentRepository.GetAll() on storeStockContent.MaterialsContentId equals materialsContent.Id
                                         join queryNode in _materialsNodeRepository.GetAll() on materialsContent.MaterialsNodeId equals queryNode.Id
                                         join queryNodeChild in _materialsNodeRepository.GetAll() on materialsContent.MaterialCategoryId equals queryNodeChild.Id
                                         join users in userData on storePutContent.StorePutPeopleId equals users.Id into Joinmu
                                         from mu in Joinmu.DefaultIfEmpty()
                                         join affirmuser in userData on storePutContent.IdentifyingPeopleId equals affirmuser.Id into JoinmuAff
                                         from muff in JoinmuAff.DefaultIfEmpty()
                                         select new StoreStockContentDto
                                         {
                                             StoreStockId = storeStock.Id,
                                             Id = storeStockContent.Id,
                                             //仓库名称
                                             StroeName = storeStockContent.StroeName,
                                             //产品图号
                                             ProductDrawingNo = storeStockContent.ProductDrawingNo,
                                             //规格型号
                                             Module = storeStockContent.Module,
                                             //产品名称
                                             ProductName = storeStockContent.ProductName,
                                             //物料细类
                                             MaterialCategory = queryNodeChild.MaterialTypeName,
                                             //物料类别
                                             MaterialsNode = queryNode.MaterialTypeName,
                                             //MaterialsPropertyName = storeStockContent.OutboundState == OutboundStates.在库 ? "库存" : storeStockContent.OutboundState == OutboundStates.出库 ? "已出库" : "未领料",
                                             //合格整号
                                             MaterialsProperty = (int)storeStockContent.OutboundState,
                                             QualifiedNumber = storeStockContent.QualifiedNumber,
                                             //放行单号
                                             ReleaseOrder = storeStockContent.ReleaseOrder,
                                             //质控卡号
                                             QCCardNo = storePutContent.QCCardNo,
                                             //发次
                                             SendTime = storeStockContent.SendTime,
                                             //批次
                                             Batch = storeStockContent.Batch,
                                             //合格证任务号
                                             QualifiedTaskNumber = storePutContent.QualifiedTaskNumber,
                                             //装配任务号
                                             AssemblyTaskNumber = storePutContent.AssemblyTaskNumber,
                                             //数量
                                             Quantity = 1,
                                             //产品编号
                                             ProductNumber = storeStockContent.ProductNumber,
                                             //有效期止
                                             ExpirationDate = storeStockContent.ExpirationDate == "2099-01-01T00:00:00.000Z" ? null : storeStockContent.ExpirationDate,
                                             //入库人
                                             StorePutPeople = mu.Surname + mu.Name,
                                             //入库时间
                                             StorePutTime = storePutContent.StorePutTime,
                                             //
                                             Remark = storePutContent.Remark,
                                             //确认时间
                                             IdentifyingTime = storePutContent.IdentifyingTime,
                                             //确认人
                                             IdentifyingPeople = mu.Surname + mu.Name,
                                             SuitStuts = storeStockContent.IsSuit == (IsSuits)1 ? "配套" : "",
                                             IsSuit = (int)storeStockContent.IsSuit,
                                             StorePutContentId = storePutContent.Id,
                                             BinLocation = storeStockContent.BinLocation,
                                             ProductCode = storeStockContent.ProductCode,
                                             SendTimeId = storeStockContent.SendTimeId,
                                             BomAnalysecontentId = storeStockContent.BomAnalysecontentId,
                                             LoadDetailsId = storeStockContent.LoadDetailsId,
                                             DesignatedModule = storeStockContent.DesignatedModule,
                                             DesignatedSendTime = storeStockContent.DesignatedSendTime,
                                             BinLocationId = storeStockContent.BinLocationId,
                                             ProductCodeId = storeStockContent.ProductCodeId,
                                             IsPreSuit = (int)storeStockContent.IsPreSuit,
                                             MaterialsContentId = storeStockContent.MaterialsContentId,
                                             StoreId = storeStockContent.StoreId,
                                             DesignatedXJ = storeStockContent.DesignatedXJ,
                                             DesignatedXJCode = storeStockContent.DesignatedXJCode,
                                             Years = storeStockContent.Years,
                                             PreSuiteName = storeStockContent.PreSuiteName, //add 12/2
                                             PreSuiteTime = storeStockContent.PreSuiteTime, //add 12/2
                                             CompletePeople = storeStockContent.CompletePeople, //add 12/2
                                             CompleteTime = storeStockContent.CompleteTime, //add 12/2
                                             CreationTime = storeStockContent.CreationTime //add 12/6

                                         };
            return querybomAnalyseContent.OrderByDescending(t => t.CreationTime).ToList(); //add 12/6
        }
        /// <summary>
        /// 查找当前节点类型 1 任务-节点  2 节点-节点 3 节点-工序 4 工序-工步 5 工步
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public int GetRouteType(Guid ParentId)
        {
            var bopDesc = _bopDescRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (bopDesc != null)
            {
                return 1;
            }
            var bopNode = _bopNodeRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (bopNode != null)
            {
                if (!string.IsNullOrEmpty(bopNode.ProcessCode))
                {
                    return 3;
                }
                else
                {
                    return 2;
                }
            }
            var processEntity = _processesEntityRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (processEntity != null)
            {
                return 4;
            }
            var workEntity = _workStepEntityRepository.GetAll().Where(d => d.Id == ParentId).FirstOrDefault();
            if (workEntity != null)
            {
                return 5;
            }
            return 0;
        }
        /// <summary>
        /// 得到预配套状态
        /// </summary>
        /// <param name="preSuiteStock">配套数量</param>
        /// <param name="bomDosageTotalAmount">芯级用量</param>
        /// <param name="UsableMatingQuantityStock">可用库存数量</param>
        /// <returns></returns>
        private int GetPreStatus(decimal preSuiteStock, decimal bomDosageTotalAmount, decimal UsableMatingQuantityStock)
        {
            if (preSuiteStock == 0)
            {
                return (int)AssortStatus.未配套;
            }
            else if (bomDosageTotalAmount - preSuiteStock <= UsableMatingQuantityStock)
            {
                return (int)AssortStatus.配套中;
            }
            else if (bomDosageTotalAmount == preSuiteStock)
            {
                return (int)AssortStatus.已配套;
            }
            else if (bomDosageTotalAmount - preSuiteStock > UsableMatingQuantityStock)
            {
                return (int)AssortStatus.缺料;
            }
            return 0;
        }

        /// <summary>
        /// 根据枚举获取枚举描述信息
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static string GetEnumDesc(System.Enum parm)
        {
            FieldInfo enumInfo = parm.GetType().GetField(parm.ToString());
            if (enumInfo == null)
            {
                return "";
            }
            DescriptionAttribute[] enumAttributes
                = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (enumAttributes.Length > 0)
            {
                return enumAttributes[0].Description;
            }
            return parm.ToString();
        }


    }
}
